Lua继承的一个例子
2016-11-12 18:33
417 查看
如果看懂了这个就能明白通过metatable在继承的意义,也能理解:和.的差异。
输出信息
先将代码贴出来,今后来做解释。
main.lua
require("base") require("actor") function main() local obj = actor.new("tiny") obj:init() obj:say_hi() obj:work() end main()
base.lua
_G.base = { init = function(self) self.x = 10 self.y = 10 print("base.lua init") end, say_hi = function(self) print( string.format("base.lua say_hi x: %d, y: %d",self.x,self.y)) end, work = function(self) print("this is base work") end }
actor.lua
_G.actor = {} setmetatable(_G.actor,{__index = _G.base }) function new(name) obj = {name = name} setmetatable(obj,{__index = _G.actor }) return obj end function init(self) getmetatable(getmetatable(self).__index).__index.init(self) self.hp = 10 end function say_hi(self) getmetatable(getmetatable(self).__index).__index.say_hi(self) print(string.format("actor this is actor:say_hi, hp: %d", self.hp)) end _G.actor.new = new _G.actor.init = init _G.actor.say_hi = say_hi
输出信息
base.lua init base.lua say_hi x: 10, y: 10 actor this is actor:say_hi, hp: 10 this is base work
先将代码贴出来,今后来做解释。
相关文章推荐
- C++ 类继承的一个例子
- 关于私有继承的一个小例子
- luajava数值和对象传递的一个例子
- js面向对象编程,一个完整的继承例子
- Javascript 进阶 面向对象编程 继承的一个例子
- 一个例子,理解java中的继承(来自《疯狂java讲义》)
- 定义一个继承层次的例子-Shape类Circle类的定义
- 用lua写一个闭包的例子(lua语言)
- cocos2dx lua 多重继承例子
- 类继承一个简单的例子
- 48、C++ Primer 4th 笔记,句柄类,继承,虚函数等的一个综合例子(未完)
- 一个例子对于类继承和关键字“this”的理解
- 一个Lua coroutine的例子
- java继承的一个小例子
- 多态继承的一个小例子,mark一下。
- 一个简单继承的例子,面试失败的教训
- 用 c 语言实现类的继承,并且可用父类指针操作子类对像的一个测试例子
- lua 一个简单的继承/派生关系
- Javascript 进阶 面向对象编程 继承的一个例子
- 关于继承和多态的一个简单例子