You have the arguments of setmetatable backwards. The first argument is the table you want to assign a metatable to, the second argument is the table that will be the metatable of the first argument.
tab is myTable’s metatable and contains the metamethods? But whenever you index a nil value in myTable, how does tab fire then? That’s the confusion I have.
incap you’re doing a bad job of explaining this smh.
The metatable and base table aren’t the same table. When you do setmetatable, you’re telling the Lua interpreter that myTable should follow tab’s rules.
__index works when you do t.k, index’s function parses the table itself and the key you’re attemping to index.
You can also set __index to another table
I dont understand fully what you mean but the index would just return nil
if foo.bar is nil then it would return nil
print(foo.bar) → nil
If you mean in the context of inheritence, (and you have the __index set to another table), it looks in that table aswell for a value. It will still return nil if it cant find it there either
local tab1 = {a = 1}
local tab2 = setmetatable({}, {__index = tab1})
print(tab2.a) --> 1 Even though tab2 doesn't have an a key, it can find it because it exists in the __index pointer
It merely just points Lua to another table when either making a new index, or indexing an existing one. As far as I know, these are the only two that will accept a table value.