lua 面向对象
2014-04-04 14:20
387 查看
封装成对象调lua
用copyObj拷贝数据来创建新对象
目的是new出来的每个对象有自己独立的数据
包括它的基类数据也独立出来
----------定义到此结束----------------
用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的表,在子类中也是独立的。
相关文章推荐
- lua 一个简单的继承/派生关系
- lua 5.1参考手册
- [LeetCode] Evaluate Reverse Polish Notation
- lua错误总结
- lua中字符串匹配
- Lua string
- Lua模式匹配
- Lua中的pairs们(pairs,ipairs,gmatch)
- KopiLua and LuaInterface
- lua语言学习(2.0)(终章)
- lua开篇
- Lua 函数作为参数传递时的注意事项
- Lua闭包(closure)示例
- Lua 学习记事本
- 327 - Evaluating Simple C Expressions
- Wax 将Lua带人iPhone开发
- lua开发工具
- lua与c互调--lua调用c
- lua与c互调--c调用lua
- Lua5.1编程二:Lua高级特性