通过函数闭包的方式来实现面向对象
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 end12 init()13 return self14 end15 16 --local p = People("XiaoLi")17 --p:sayHi()18 19 -- 继承20 function Man(name)21 22 local function init()23 24 end25 26 local self = People(name)27 28 self.sayHi() -- 调用父类的函数29 30 self.sayHi = function()31 print("重写父类的函数 sayHi")32 end33 return self34 end35 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 end10 11 function copy(dist,tab)12 for key, var in pairs(tab) do13 dist[key] = var14 end15 end16 17 People ={}18 19 function People.sayHi(self)20 print("People sayHi"..self.name) -- .. 表示字符串连接21 end22 23 People.new = function(name)24 local self = clone(People)25 self.name = name26 27 return self28 end29 --30 --local p = clone(People)31 --p.sayHi()32 33 local p = People.new("Jinpp")34 -- p.sayHi(p) -- 运行结果 People sayHiJinpp35 p:sayHi() -- 运行结果 People sayHiJinpp36 37 38 -- 类的继承39 Man = {}40 Man.new = function(name)41 local self = People.new(name)42 copy(self,Man)43 return self44 end45 --46 Man.sayHello = function()47 print("Man say Hello")48 end49 50 -- 函数的重写51 Man.sayHi = function(self)52 print("Man sayHi "..self.name)53 end54 55 local m = Man.new("Lisi")56 m:sayHello()57 m:sayHi()
蛮简单的特别好理解。2016年01月24日21:43:39