I feel like every other explanation is so close to actually answering it, except it never does.
First of all, what the heck does __index really do? I don't want an analogy, just give it to me straight. The most I understand is that it's used to reference a key to another table if the original key doesn't have that. But why would you ever want that? When would that ever happen, where you have an empty key, but need a value to it? You have a missing user ID in the User datastore, so you check the Premium User datastore? And I doubt that's very likely to happen.
Secondly, why do stuff like:
local class = {} class.__index = class function class.new() ... end
when it works just fine without "class.__index = class"? The function's already logged into the table, there's literally no way (besides hardware glitches) you'd not get the correct function when you call for it.
I'm just so confused on why you want to do this. Everyone keeps telling to do it, but never explaining why.
Figured It Out After hours of research, I've finally figured out what the crap this does. It's to bring in the class functions to an object. Sorry if this is a bit a rushed, but I'm more than a bit angry that so many people couldn't have said this simple thing instead.
So when you first create an object from a class in this example and initialize it (giving it it's own individual properties, like how a cat has 4 legs.):
local Entity = {} function Entity.New(name) local new_entity = {} new_entity.Name = name return new_entity end function Entity:Walk(speed) self.Speed = speed end local dog = Entity.New("dog") dog:Walk(5)
This'll throw an error message telling you that dog;Walk() is nil, meaning that it doesn't exist. Confusing, right? Because since this is prototypal inheritance (don't worry too much about this, but it's basically normal class inheritance such as in python but the object doesn't inherit everything in the original class), it know's nothing about the Walk function.
To do this, we gotta set its metatable to the class (it basically makes the object become a subclass of the metatable). Now we could do it inside the new function by setmetatable(new_entity, Entity)
, but it appears that doing Entity.__index = Entity
appears to be just syntax sugar (just a style of code). Now if we add that code, the code will execute completely.
This seems to be out of the "Roblox Lua" API but taking some information from here and here it is used for some useful aspects. You might have been misinformed to what it does is what brings up your question.
When calling the "__index" it actually refers to when adding information to a new metatable of the same class it automatically adds-in that extra piece of required data for you. Finding a way to use this is up to you. :)
Final Edit: For anyone looking for a quick definition this is just a function that runs when you add something to the table.
If you have any questions or issues please contact me.