Lua面向对象 --- 多继承
工程目录结构:

ParentMother.lua:
1 ParentMother = {} 2 3 function ParentMother:MortherName() 4 print("Morther name : HanMeimei") 5 end 6 7 return ParentMother
ParentFather.lua:
1 ParentFather = {} 2 3 function ParentFather:FatherName() 4 print("Father name : LiLei") 5 end 6 7 return ParentFather
Daughter.lua:
1 require "ParentMother" 2 require "ParentFather" 3 4 Daughter = {} 5 6 --不是 Daughter 中一个方法 7 local function Search(key,BaseList) 8 for i=1,#BaseList do 9 local val = BaseList[i][key] 10 if val then 11 return val 12 end 13 end 14 return nil 15 end 16 17 --不是 Daughter 中一个方法 18 local function CreateClass() 19 local parents = {ParentMother,ParentFather} 20 setmetatable(Daughter, 21 { 22 __index = function(t,k) 23 return Search(k,parents) 24 end 25 }) 26 end 27 28 29 30 function Daughter:new() 31 local self = {} 32 CreateClass() 33 setmetatable(self,{__index = Daughter}) 34 Daughter.__index = Daughter 35 return self 36 end 37 38 function Daughter:DaugtherName() 39 print("Daugther name : Linda") 40 end 41 42 return Daughter 43 44 --[[ 45 Lua多继承的实现原理: 46 也是利用的元表和元表的__index字段,不同于对象实例化和单一继承不同的是__index字段赋值的是一个函数而不是一个基类的表。 47 利用传入__index字段的函数来查找类中找不到的字段(函数中遍历该类继承的多个基类) 48 --]]
Main.lua:
1 require "Daughter" 2 3 local child = Daughter:new() 4 child:DaugtherName() 5 child:MortherName() 6 child:FatherName() 7 8 --[[ 9 运行结果: 10 Daugther name : Linda 11 Morther name : HanMeimei 12 Father name : LiLei 13 --]]
码云上的相关工程:https://gitee.com/luguoshuai/LearnLua
新追加的,另外一种实现多重继承的方式:
1 Animal = {} 2 function Animal:ShowType() 3 print("the is a animal!") 4 end 5 6 7 World = {} 8 function World:ShowPosition() 9 print("on the earth!") 10 end 11 12 13 local function Search(k, list) 14 for i=1,#list do 15 local tmpVal = list[i][k] 16 if tmpVal then 17 return tmpVal 18 end 19 end 20 return nil 21 end 22 23 24 local function CreateClass( ... ) 25 local tab = {} 26 setmetatable(tab,{__index = function (_,k) 27 return Search(k, arg) 28 end}) 29 30 tab.__index = tab 31 32 function tab:new(o) 33 o = o or {} 34 setmetatable(o,tab) 35 return o 36 end 37 38 return tab 39 end 40 41 TestClass = CreateClass(Animal, World) 42 43 local lgs= TestClass:new({"12"}) 44 lgs:ShowType();
运行结果:


浙公网安备 33010602011771号