您的位置:首页 > 编程语言 > Lua

lua 面向对象

2014-04-04 14:20 387 查看
封装成对象调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的表,在子类中也是独立的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: