Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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.

4 comments

0

No I mean will __index fire if I do table:function()

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...

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.

0

Is there a way to do it indexed?

This discussion is preserved as it was. New answers, comments, and votes are closed.