can anyone explain what table.__index = table does, I have seen alot of people use it when creating custom classes with OOP, but I have no idea what it actually does. I know what the __index metamethod does but I really dont know why they'd use it like that.
like this
local a = {} a.__index = a
I have seen this tutorial https://devforum.roblox.com/t/all-about-object-oriented-programming/8585 but it doesnt explain well of what it does.
what does
table.__index = table
do when doing OOP?
The same thing when not doing OOP.
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.
local class = {} --// new table for class class.__index = class --// have class be our metatable too by setting a metamethod to it function class.new(...) --// our `.new` constructor for creating objects local newObject = {...} --// define array with all indexes being arguments passed to `.new` setmetatable(newObject, class) --// set metatable return newObject --// return our new object for OOP usage end function class:myMethod() --// custom method return #self --// return length of self end local myNewObject = class.new("a", "b", "c") --// new object from class's `.new` constructor print(myNewObject:myMethod()) --// print's 3 because length of table is `3`
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.
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!