local Class = {}
Class.__index = Class
--default implementation
function Class:new() print("Bye!!") end
--create a new Class type from our base class
function Class:derive(type)
local cls = {}
cls.type = type
cls.__index = cls
cls.super = self
setmetatable(cls, self)
return cls
end
function Class:__call(...)
local inst = setmetatable({},self)
inst:new(...)
return inst
end
function Class:get_type()
return self.type
end
--Create 'Player' class
local Player = Class:derive("Player")
function Player:new(name)
print("hello " .. name)
end
--Create player instance
plyr1 = Player('Dylan')
这是lua中的一个类模块
我有几个问题。
如果 Class:new() 什么都不做,它的意义何在?
在 Class:__call(...) 函数的第 19 行 inst:new(...) 中,为什么程序在 Player 表中搜索 :new 函数而不是原始 Class 表?
意思是,当调用 Player("Dylan") 时,会打印“Hello Dylan”而不是“Bye!!”
inst table的meta table不是设置为self,引用Class吗?
代码取自关于 Lua 类的 youtube 视频https://www.youtube.com/watch?v=O15GoH7SDn0
这样做时,Player("Bob")
我们将输入__call
元表中定义的元方法,Player
其中Class:__call
function Class:__call(...)
local inst = setmetatable({},self)
inst:new(...)
return inst
end
在这个调用self
中是指Player
表而不是Class
表,所以当我们创建时inst
我们设置它的元表,Player
它有一个__index
指向自身的值,所以inst:new
将等于Player.new(inst, name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句