__call

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; additional arguments are simply dropped. Functables are an easy way to couple state with a function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.12