I'm still a little newbie with metatables, and there is something that makes me confused
when I use metamethods like __index
and __newindex
in my metatable, they are only called when I invoke an element of the table as follows:
print(table[index]) -- this call the __index
table[index] = value -- this call the __newindex
but these two metamethods are not called when I invoke an element of the table as follows:
print(table.index) -- this does NOT call __index
table.index = value -- this does NOT call __newindex
my question is, is there any way to make table.index
also call these two metamethods? or does only table[index]
work?
Yes, __index will work with both brackets: mytable["index"]
as well as the dot operator: mytable.index
mytable = setmetatable({}, { __index = function(t, k)
if k == "index" then
return "works fine"
end
return rawget(t, k)
end })
print(mytable["index"])
print(mytable.index)
You can circumvent the preset metatable methods using rawget and rawset
Having said that, if you are new to Lua I recommend looking for simple solutions that work WITHOUT metatables.