Hello, I was wondering how these two snippets of code differed and if they were just the same thing but different code. If I did something like local table = {} and local newtable = {} then newtable.__index = table and setmetatable(newtable,table), whats the difference between those two snippets of code? I understand the setmetatable is just setting the metatable, but what is the newtable.__index = table doing in the background?
✓ ANSWER ACCEPTED
How does this metamethod related snippet of code work?
1 answer
✓ Accepted answer
__index is a metamethod that calls when someone indexes a table. It can be a table or function. If it's a table then it will just index the table, but if it's a function then it's a bit more complicated. The function takes one argument, "key". But do note you should also make sure you're using self. self is just the table it(self) and key is what they're indexing. The return value is what they will get back.
Example:
local MyTable = {1,2,3,4}
local MT = {}
function MT.__index(self, key)
if key:lower() == "hello" then
return 1
end
return self[key]
end
setmetatable(MyTable, MT)
print(MyTable["hello"])
-- Output:
-- 1
Fun facts: This is heavily used in Lua OOP. The function rawget completely bypasses the metatable.
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Even if you aren't asking for help with an error in some code, its still best to use inline code blocks when asking questions.