Reputation: 616
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?
Upvotes: 0
Views: 1144
Reputation: 89
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.
Upvotes: 2
Reputation: 7046
the __idnex
and __newindex
metamethods only get used when the table doesn't have an element at the index in question. If there's already an element, indexing will just return that element and setting it will just overwrite the existing element.
If you want complete control over all indices in a table, you have to keep it 100% empty and save all its values in another table and access those using the metamethods.
Upvotes: 1