Generally, people use it in OOP so they can create a new instance of the class with setmetatable. For example:
local Class = {Value = 5}
Class.__index = Class; --// Points to the Class itself and it's properties
function Class.new()
return setmetatable({}, Class); --// Creates a new instance, will not affect the actual Class
end
function Class:GetValue()
return self.Value --// self = Class
end
print(Class.new():GetValue()) --// 5, GetValue works since __index grabs it
That won’t work. That calls print("No value found") and sets Table.__index to the value that print returns, aka nil.
You can set __index to a table or a function. The function will be called with table, index if they index something that’s not actually part of the main table, and the __index table will be indexed with the index if it’s not a part of the main table.
True, not really thinking much about it. You need to set it as a function i.e function() print(“whatever u want”) end. Afaik there’s no reason to set the Table to itself there.
They’re probably using the Table itself as a metatable for a different table, like in the class example ReturnedTrue gave where the class is a metatable for each instance of that class.
I don’t really get why that wouldn’t work without the __index line. Wouldn’t GetValue search the empty table for Value, not find it, then search for metatables, then finding Class as a metatables realize that Value is a valid member of Class and print 5? I don’t get why that __index line does anything.