On 5/24/2012 10:25 PM, Emeka wrote:
> What is the essence of the
below?
>
> local Request = {}
> Request.__index = Request
The above doesn't do anything interesting by itself, though if
Request is later assigned as the metatable for another table, AND
the Request table had another member, it would be relevant:
local aRequest = {}
setmetatable( aRequest, Request ); -- Request is now the metatable
of the table referred to by "aRequest"
function Request:someFunction()
print("a function on Request")
end
aRequest:someFunction()
The __index metamethod tells Lua what to do if someone tries to look
up an undefined key on a table. If __index is a function, it gets
called. If __index is a table, then it looks for the key in that
table. So when Lua can't find a member on aRequest, it tries the
__index metamethod, sees that it's a table, finds the key
"someFunction" on that table, and then tries to call it as a
function.
Tim