Method/1
Dog = {}
function Dog:new()
local newObj = {sound = 'woof'}
return setmetatable(newObj, { __index = self })
end
Method/2
Dog = {}
function Dog:new()
local newObj = {sound = 'woof'}
self.__index = self
return setmetatable(newObj, self)
end
Most of the times I have seen people using the self.__index = self method, which to me seems clumsy. Why pass the whole Dog object with all the additional methods which doesn't constitute a metatable to setmetatable? Method/1 is good for setting the new objects's metatable.__index to the Dog object, it is also cleaner.
Is there a good reason to use Method/2 instead of Method/1?
Some additional code to provide context, it works with both methods
function Dog:makeSound()
print('I say ' .. self.sound)
end
mrDog = Dog:new()
mrDog:makeSound()
Method/2 is a little more optimized than Method/1 because it doesn't need to create an extra table as its metatable. It uses itself as the metatable.
Since you said that you think Method/1 is cleaner in your question, feel free to use it. I don't think the performance difference between the two would matter in most cases. Readability is almost always more important.