工程目录结构: 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:FatherN
工程目录结构:
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