lua中的类功能(面向对象2)

来源:互联网 发布:30岁程序员vs公务员 编辑:程序博客网 时间:2024/05/21 22:34

我项目中,lua使用类功能的方法:

--提供lua中class功能,目前有集成,多态的功能,析构需要实现local _class={}function bbclass(super) --参数super为父类,表示继承local class_type={}class_type.constructor=false    class_type.destructor=falseclass_type.super=super       --父类class_type.new=function(...) --创建对象方法,返回该类一个新对象local obj={}dolocal createcreate = function(c,...)if c.super then  --如果这个类有父类create(c.super,...)endif c.constructor then --构造函数不为空--构造函数,dnmission:constructor()相当于dnmission.construct(self)c.constructor(obj,...) endend--设置元表,使对象字段未赋值时,读类的默认值setmetatable(obj,{ __index=_class[class_type] })create(class_type,...)endreturn objend    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]=vend}) if super thensetmetatable(vtbl,{__index=function(t,k)local ret=_class[super][k]vtbl[k] = retreturn retend})end return class_typeend


然后,新建类:

dnmission = bbclass()function dnmission:constructor()print("dnmission:constructor")self.id = 0self.state = 0self.type = 0self.category = 0endfunction dnmission:destructor()print("dnmission:destructor")end


然后新建对象:

local mission=dnmission.new()




0 0