✓ Accepted answer
####Accept this answer if it helped!
##Question
what does table.__index = table do when doing OOP?
##Answer
The same thing when not doing OOP.
###Why do people do this?
When creating classes, people set the newly created object's metatable to the original table containing the construction constructor (usually `.new)
Why do this? Well you save on having to redefine new functions every class creation.
###Example
local class = {}
class.__index = class
function class.new(...)
local newObject = {...}
setmetatable(newObject, class)
return newObject
end
function class:myMethod()
return #self
end
local myNewObject = class.new("a", "b", "c")
print(myNewObject:myMethod())
####Why does this example work?
Well in the example, you may see that we are using self and may be saying "but that just references back to our class variable!" and then probably "why is it printing '3'? Well in metatables though self is set to the owner of the metatable, in this case newObject is the owner of the metatable . (cite line 5) This is also why you would want to use table.__index = table since without setting the metatable, self will just reference back to the original class table.
###Should you do this?
Up to you, but I suggest using it because its my preference and its cooler. There might be other advantages i'm not covering, try seeing if anyone else answers!
2 comments
I'm amazed incapaxx didn't post an answer yet, i'll write one.
Anyways, good question I never seen this one asked and I myself argued with a friend about the usage of
a.__index = a