lua 面向对象

封装成对象调lua

用copyObj拷贝数据来创建新对象

目的是new出来的每个对象有自己独立的数据

包括它的基类数据也独立出来


function copyObj(obj)
	local tab = {}
	for k, v in pairs(obj or {}) do
		if type(v) ~= "table" then
			tab[k] = v
		else
			tab[k] = copyTab(v) -- 深层嵌套查找
		end
	end
	local mt = getmetatable(obj)
	if(mt)
	then
		mt = copyObj(mt) --把对象的元表一起拷贝到新对象
		setmetatable(tab,mt)
	end
	return tab
end

a = { name = 'this is a',x=1, tb = {k1=1}}

function a:fun()
print(self.name)
end


function a:new()
return copyObj(a)
end


b = { name = 'this is b' }
setmetatable(b,{__index = a}) -- 设置b继承a


function b:new() 
return copyObj(b) 
end


----------定义到此结束----------------
local b1 = b:new()
local b2 = b:new()


b1:fun() --输出'this is new b' 实现以继承关系,谁调用,优先取谁的成员,
b1.name = 'this is new b'
b2:fun() --输出'this is new b',由于是拷贝出来的对象,数据独立

print(b1.x)
b1.x=2
print(b1.x) --输出1,x是基类a的成员,在子类中也是独立的。

print(b1.tb.k1)
b1.tb.k1=2
print(b1.tb.k1)--输出2
print(b2.tb.k1) --输出1,tb.k1是基类a的表,在子类中也是独立的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值