lua-users home
lua-l archive

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

On 26 December 2015 at 21:20, Marc Balmer <> wrote:
> I have C API question:
> In a first metatable I set the __index field to a function that checks if the key is a number.  If it is, it returns some data value, nil otherwise.  Now I want to nest a second metatable, that has a table of functions at the __index field.
> I don't seem to get that to work. The functions in the second metatable are never called. I am probably setting the metatable on the wrong field of the first metatable.  So on which field of the first metatable do I set the second metatable, on the metatable itseld, the __index field or the (C) function returning either a value or nil?
> Do some C examples of such nesting exist anywhere?
> Thanks,
> Marc

What do you mean "second metatable"?
You cannot have two __index metamethods for a single object.
You *could* "chain" them though

via either just using a function:
setmetatable({}, {__index=function(t,k) local v = foo[k]; if v == nil
then v = bar[k] end return v end})

Or via a second table (with it's own metatable):
local foo = {}
local bar = {}
setmetatable(foo, {__index=bar})
setmetatable({}, {__index=foo})

Both should be straightforward to create via the C api.