我项目中,lua使用类功能的方法:
--提供lua中class功能,目前有集成,多态的功能,析构需要实现
local _class={}
function bbclass(super) --参数super为父类,表示继承
local class_type={}
class_type.constructor=false
class_type.destructor=false
class_type.super=super --父类
class_type.new=function(...) --创建对象方法,返回该类一个新对象
local obj={}
do
local create
create = function(c,...)
if c.super then --如果这个类有父类
create(c.super,...)
end
if c.constructor then --构造函数不为空
--构造函数,dnmission:constructor()相当于dnmission.construct(self)
c.constructor(obj,...)
end
end
--设置元表,使对象字段未赋值时,读类的默认值
setmetatable(obj,{ __index=_class[class_type] })
create(class_type,...)
end
return obj
end
class_type.delete=function(obj)
do
local remove = nil
remove = function(c,...)
--log(c.destructor)
if c.destructor then
c.destructor(obj, ...)
end
if c.super then
remove(c.super, ...)
end
end
--TODO:这里应该有内存泄漏
remove(class_type)
end
end
local vtbl={}
_class[class_type]=vtbl
setmetatable(class_type,{__newindex=
function(t,k,v)
vtbl[k]=v
end
})
if super then
setmetatable(vtbl,{__index=
function(t,k)
local ret=_class[super][k]
vtbl[k] = ret
return ret
end
})
end
return class_type
end
dnmission = bbclass()
function dnmission:constructor()
print("dnmission:constructor")
self.id = 0
self.state = 0
self.type = 0
self.category = 0
end
function dnmission:destructor()
print("dnmission:destructor")
end
local mission=dnmission.new()