July 2018
Beginner
202 pages
5h 42m
English
The __call meta method lets a table be used as a function. In some languages, this construct is referred to as a functor; in Lua it's called a functable.
The __call meta method has a variable number of arguments. The first argument is the table being treated as a function; this is followed by any number of arguments that the functable actually takes. Let's see this in action:
tbl = { __call = function(table, val1, val2) return "Hello, from functor: " .. (val1 + val2) end}setmetatable(tbl, tbl)message = tbl(2, 3); -- Calling the table like a function!print ("message: " .. message)
You can pass less arguments to the functable; any arguments not present will simply receive a nil value. You can also pass more arguments to the functable; ...