Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Do metatables work on methods (e.g. table:function)?

Asked by 6 years ago

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")

1 answer

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

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.

0
No I mean will __index fire if I do table:function() User#22219 20 — 6y
0
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... NewVoids 97 — 6y
0
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. NewVoids 97 — 6y
0
Is there a way to do it indexed? User#22219 20 — 6y
Ad

Answer this question