Hi there, I was wondering if there was any difference when you set a table’s metatable with the metamethod __index = object and using just object itself.
See below as example:
local object = {}
object.__index = object
function object.new()
local self = {}
self.abc = 123
setmetatable(self,{__index = object}) -- notice metamethod here
return self
end
compared to:
local object = {}
object.__index = object
function object.new()
local self = {}
self.abc = 123
setmetatable(self,object) -- notice it's just object and not __index = object
return self
end
There is no difference, its just how the metatable is being applied.
So when you are applying the metatable in the second Argument, you are basically telling the code to create a metatable within that Array that has the __index metamethod inside, so basically this is what the second Example is:
Array = {__index = Array} -- Metamethod specified
-- Array.__index = Array is Basically the same thing as the line above.
setmetatable(self, Array) -- creates metatable from Array
Compared to the first:
Array = {}
-- doesnt require a specified metamethod
setmetatable(self, {__index = Array})
--[[
Applies metatable without the Variable while creating a new table
for the metatable.
--]]
The First method is more cleaner in my opinion, however it is up to you.