LUA面向对象浅析
2013-03-11 09:38
441 查看
--表 元表 元方法结合起来可以实现lua面向对象的机制
--lua中通过原型的思路才使用实现对象的实例化机制
--一个原型表可以用来描述一个类 在原型表中填写属性和方法
--实例化对象,创建一个新表,将新表的元表设置为原型表.将原型表的__index指向自身
--类似js的面向对象机制
--LUA中内置的面向对象的机制
结果为:{20,10,40,30,50}
--lua中通过原型的思路才使用实现对象的实例化机制
--一个原型表可以用来描述一个类 在原型表中填写属性和方法
--实例化对象,创建一个新表,将新表的元表设置为原型表.将原型表的__index指向自身
--类似js的面向对象机制
function Human(name) local this={ name=name, a=1, b=2, c=3, d=4 } this.eat=function(food) print(this.name.." eats "..food) end this.add=function(n) this.a,this.b,this.c,this.d=this.a+n,this.b+n,this.c+n,this.d+n end this.getName=function() print("my name is "..this.name) end this.print=function() print(this.a,this.b,this.c,this.d) end return this end a=Human("Hover") b=Human("Lees") a.eat("meat bun") b.eat("sweet bun") a.add(1) b.add(2) a.getName() a.print() b.getName() b.print() --[[ my name is Hover 2 3 4 5 my name is Lees 3 4 5 6 ]]
--LUA中内置的面向对象的机制
Set={} local mt={} function Set.new(l) local set={} setmetatable(set,mt)--设置对象的元表 之后通过对元表的操作来使对象具有其他的操作行为 for _,v in ipairs(l) do set[v]=true end return set end function Set.union(a,b) local res=Set.new{} for k in pairs(a) do res[k]=true end for k in pairs(b) do res[k]=true end return res end function Set.intersection(a,b) local res=Set.new{} for k in pairs(a) do res[k]=b[k] end return res end function Set.tostring(set) local l={} for e in pairs(set) do l[#l+1]=e end return "{"..table.concat(l,",").."}" end function Set.print(s) print(Set.tostring(s)) end s1=Set.new{10,20,30,40} s2=Set.new{10,50} print(Set.print(Set.union(s1,s2)))
结果为:{20,10,40,30,50}
相关文章推荐
- Lua面向对象之类和继承浅析
- Lua面向对象之类和继承浅析
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- lua面向对象详解(1)
- LUA面向对象程序设计(四)多重继承
- lua面向对象类,继承和多重继承的实现
- 学习笔记-------面向对象内存浅析
- lua的面向对象
- lua的面向对象实例
- lua面向对象模拟简介
- Lua面向对象详解
- Lua知识点八 面向对象程序设计
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- lua中的面向对象模拟,类,继承,多态
- 转载和积累系列 - Lua 有趣的面向对象实现
- lua面向对象实现-类实例化对象、继承、多态、多继承、lua单例模式
- Lua笔记17 面向对象类
- 项目后期Lua接入笔记08--Lua面向对象及LuaBehaviour的再设计
- lua中的面向对象模拟,类,继承,多态
- Lua面向对象