通过函数闭包的方式来实现面向对象
1 -- 通过函数闭包的方式来实现面向对象 2 3 function People(name) 4 local self = {} 5 local function init() 6 self.name = name 7 end 8 9 self.sayHi = function() 10 print("Hello"..self.name) 11 end 12 init() 13 return self 14 end 15 16 --local p = People("XiaoLi") 17 --p:sayHi() 18 19 -- 继承 20 function Man(name) 21 22 local function init() 23 24 end 25 26 local self = People(name) 27 28 self.sayHi() -- 调用父类的函数 29 30 self.sayHi = function() 31 print("重写父类的函数 sayHi") 32 end 33 return self 34 end 35 36 local m = Man("隔壁老王") 37 m:sayHi()
通过复制表的方式来实现面向对象
1 -- Lua语言面向对象之复制表的方式面向对象 2 3 function clone(tab) 4 local ins = {} 5 for key, var in pairs(tab) do 6 ins[key] = var 7 end 8 return ins 9 end 10 11 function copy(dist,tab) 12 for key, var in pairs(tab) do 13 dist[key] = var 14 end 15 end 16 17 People ={} 18 19 function People.sayHi(self) 20 print("People sayHi"..self.name) -- .. 表示字符串连接 21 end 22 23 People.new = function(name) 24 local self = clone(People) 25 self.name = name 26 27 return self 28 end 29 -- 30 --local p = clone(People) 31 --p.sayHi() 32 33 local p = People.new("Jinpp") 34 -- p.sayHi(p) -- 运行结果 People sayHiJinpp 35 p:sayHi() -- 运行结果 People sayHiJinpp 36 37 38 -- 类的继承 39 Man = {} 40 Man.new = function(name) 41 local self = People.new(name) 42 copy(self,Man) 43 return self 44 end 45 -- 46 Man.sayHello = function() 47 print("Man say Hello") 48 end 49 50 -- 函数的重写 51 Man.sayHi = function(self) 52 print("Man sayHi "..self.name) 53 end 54 55 local m = Man.new("Lisi") 56 m:sayHello() 57 m:sayHi()
蛮简单的特别好理解。2016年01月24日21:43:39