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

我项目中,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()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值