小编Fra*_* He的帖子

Lua,用什么方式做类表和实例化?

问题来源于http://tylerneylon.com/a/learn-lua/ 教程包含代码:

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)
Run Code Online (Sandbox Code Playgroud)

这是教程中上述代码的结果:

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" …
Run Code Online (Sandbox Code Playgroud)

lua class instantiation metatable lua-table

4
推荐指数
1
解决办法
1945
查看次数

标签 统计

class ×1

instantiation ×1

lua ×1

lua-table ×1

metatable ×1