lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2010/7/19 Josh Haberman <jhaberman@gmail.com>:
> Interestingly enough, I just ran into the opposite problem.  It appears
> that my __gc method isn't respected when I do the C equivalent of:
>
> setmetatable({}, {__index = {__gc = foo}})
>
> Lua only seems to find __gc when it is set directly on the metatable.
> It doesn't find it via __index.

Like all metamethods, __gc is not looked up by an index operation on
the object itself, but by an index on its metatable. For the same
reason the following doesn't work :

local mt = {__index={__add=function(a, b) return {val=a.val+b.val} end} }
local obj1 = setmetatable({val=1}, mt)
local obj2 = setmetatable({val=2}, mt)
local obj3 = obj1 + obj2 -- throws: attempt to perform arithmetic on
local 'obj1' (a table value)

The following, on the other hand, works :

local mt = {__index={}, __add=function(a, b) return {val=a.val+b.val} end}
local obj1 = setmetatable({val=1}, mt)
local obj2 = setmetatable({val=2}, mt)
local obj3 = obj1 + obj2
assert(obj3.val == 3)

The confusion may come from the habit recommended by some people here
to have a metatable __index field point to itself.