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()
If you want an
__eq
metamethod, you must have just one metatable shared between all instances or it will not work. Your method #1 will not work in this case.But the metatable does not need to be
Dog
, it can be a dedicated metatable:Method 3.