Do metatables work on tables? I was thinking something like:
local tab = {}
local metaTab = {
__index = function(tab, i)
print(tab, i)
end)
}
function tab:test(what)
print(what)
end
setmetatable(tab, metaTab)
tab:test("wat")
Do metatables work on tables? I was thinking something like:
local tab = {}
local metaTab = {
__index = function(tab, i)
print(tab, i)
end)
}
function tab:test(what)
print(what)
end
setmetatable(tab, metaTab)
tab:test("wat")
Yes. In Lua 5.2+, that's the only thing metatables work with. In Lua 5.1 (what Roblox uses), metatables can be used with userdatas and tables.
This discussion is preserved as it was. New answers, comments, and votes are closed.
4 comments
No I mean will __index fire if I do table:function()
Oh, sorry for the late reply. The answer is yes... but not in your example. __index is only invoked when you're indexing a nil value, and tab.test isn't a nil value when you index it. Keep in mind this works because tab:test() is the same as tab.test(tab). A way to get around this would be to have a proxy and add test to the proxy instead, but still set tab's metatable to metaTab. Then, in __in...
dex index the proxy with the key that tab was indexed with, and return that value. This way, there will never be a value in tab so it'll always invoke __index. You can even set __newindex of tab to automatically insert the value into the proxy instead of tab.
Is there a way to do it indexed?