Answered by
4 years ago Edited 4 years ago
"Metatables allow tables to become more powerful than before. They are attached to data and contain values called metamethods. Metamethods are fired when a certain action is used with the datum that it is attached to."
Metatables are tables that give other tables "superpowers". Metatables tell Lua what to do during a specific situation.
What __index does?
Things start to get interesting with metatables! Let's say you wanted to create a new object.
ClassName does not exist. You have to specify a new property to make this work, which can be annoying. __index will save the day!
02 | x.ClassName = "NewObject" |
06 | local self = setmetatable ( { } , x) |
There is a situation where Lua can't find a property. You can see we tried to search ClassName, but Lua can't find anything. When we used metatables, Lua found ClassName.
__index metamethod guides Lua to the other way when that happens. When you set __index to a table, Lua will search for that table when it can't find something in the original table. When you set __index to a function, the function will fire when Lua did not found the specified index.
If you don't want __index to fire, you can use rawget, which exposes the true nature of the table.
There are more metamethods, but I don't want to go into further detail. If you have a clear understanding of metatables, you can try other metamethods such as __newindex, __tostring, __call, etc.
If you still don't understand, you can message me any time here on this website!
I recommend searching before you question since there are a lot of questions similar to yours.
https://devforum.roblox.com/t/an-introduction-to-metatables/328611 https://scriptinghelpers.org/questions/75595/metatables-what-are-they-needed-for