The question originated from http://tylerneylon.com/a/learn-lua/ The tutorial includes codes:
Dog = {dog1 = 'original dog class'}
function Dog.new(self, ... )
newObj = {sound = 'woof'}
self.__index = self
return setmetatable(newObj, self)
end
function Dog.makeSound(self, ... )
print('I say' .. self.sound)
end
print('Dog=', Dog)
print('Dog.metatable=', getmetatable(Dog)) -- this will output nothing
myDog = Dog.new(Dog)
print('\nmyDog=', myDog)
print('myDog.metatable=', getmetatable(myDog))
myDog.makeSound(myDog)
This is the result of the above codes in tutorial:
wirelessprvnat-172-17-106-141:Programming frankhe$ th test2.lua
Dog= {
makeSound : function: 0x0a6cec20
dog1 : "original dog class"
new : function: 0x0a6cec00
}
Dog.metatable= nil
myDog= {
sound : "woof"
}
myDog.metatable= {
makeSound : function: 0x0a6cec20
__index :
{
makeSound : function: 0x0a6cec20
__index :
{
makeSound : function: 0x0a6cec20
__index :
{
makeSound : function: 0x0a6cec20
__index :
{
makeSound : function: 0x0a6cec20
__index : {...}
dog1 : "original dog class"
new : function: 0x0a6cec00
}
dog1 : "original dog class"
new : function: 0x0a6cec00
}
dog1 : "original dog class"
new : function: 0x0a6cec00
}
dog1 : "original dog class"
new : function: 0x0a6cec00
}
dog1 : "original dog class"
new : function: 0x0a6cec00
}
I saywoof
One additional photo to depict the question more clearly
Although the implementation in tutorial prints ‘I saywoof’ successfully, myDog’s metatable is apparently not as desirable as we expected. Therefore my solution is below (the differences are in Dog.new):
function Dog.new(self, ... )
newObj = {sound = 'woof'}
return setmetatable(newObj, {__index = self})
end
The result of my solution:
wirelessprvnat-172-17-106-141:Programming frankhe$ th test2.lua
Dog= {
makeSound : function: 0x0d7f2978
dog1 : "original dog class"
new : function: 0x0d7f2958
}
Dog.metatable= nil
myDog= {
sound : "woof"
}
myDog.metatable= {
__index :
{
makeSound : function: 0x0d7f2978
dog1 : "original dog class"
new : function: 0x0d7f2958
}
}
I saywoof
My code prints 'I saywoof' and has a more precise table structure. I want to know which implementation is right, the one in tutorial or mine? In addition, I want to know why the code in tutorial generates an iterative definition of Dog's metatable.