Hi, i wan’t to know what means table.__index = table, i know what .__index does, this fire when table is indexed by something that doesn’t exist inside table, but what table.__index = table does???
It’s a metamethod.
You can check out the metatable documentation here:
i saw that, but i wan’t exactly what mean only this line that table.__index = table
i used __index to define new values, but this is something i don’t understand
Scroll down in the documentation, it has an info section that describes all the metamethods including __index.
but i know what __index does, i don’t know what means table.__index = table for me it’s like assigning every nil value to the same table
lets say, we have:
local Metatable = {
Value = "e"
}
Metatable.__index = Metatable -- using __index
local Table = setmetatable({}, Metatable)
print(Table.Value) -- "Value doesn't exist in Table" __index handles this by trying to find out the value inside the metatable
table.__index is usually used in OOP where if a method or an index inside a table doesn’t exist, it searches the index from the given table or the function.
For example:
local tableA = {
carrot = "carrots!"
}
local tableB = {
cake = "cakes!"
}
local newMetatable = setmetatable(tableA, {__index = tableB}) -- Setting the metatable
print(newMetatable["cake"]) -- "cake" key doesn't exist in tableA, but we used __index method to route it to tableB which has the "cake" key, thus printing "cakes!"
essentially what table.__index = table does it that if you try to index an object and the value is nil, then it will try to also look at the metatable and try finding the value there
ok, soo if the value don’t exist in our table, then it’s search for value inside metatable to fill gap? yea?
Yup! That’s what it will try to do
can i have one question more?, where can i use other metamethoods other than this???
__index is fired when a table[index] is nil, so when you index a table with a value that doesn’t exist in that table, it will search through the given table instead.
Check out the documentation that I gave you.
ok thank you, now i understand it
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.