Son继承Fathter,Monther,Father和Monther继承People
单继承实现
People.lua
local People = {}
function People:new()
-- body
local Obj = {} --创建新的表作为实例的对象
setmetatable(Obj,{__index=People}) --设置People为对象原表的__index
return Obj --返回对象
end
function People:setHeight()
-- body
end
function People:getHeight()
-- body
print("People getHeight")
end
return People
Father.lua
local People=require("People.lua")
local Father = {}
function Father:new()
-- body
setmetatable(Father,{__index=People})
local Obj = {}
setmetatable(Obj,{__index=Father})
return Obj
end
function Father:getHeight()
-- body
print("Father:getHeight")
end
return Father
Monther.lua
local People=require("People.lua")
local Monther = {}
function Monther:new()
-- body
setmetatable(Monther,{__index=People})
local Obj = {}
setmetatable(Obj,{__index=Monther})
return Obj
end
function Monther:getMoney()
-- body
print("Monther:getMoney")
end
return Monther
Son.lua
--查找函数
local function search(k,plist)
for i=1,#plist do
local v = plist[i][k] --查找函数
if v then return v end
end
end
local Son = {}
Father = require("Father")
Monther = require("Monther")
local function createClass()
local parent = {Father,Monther} --基类
setmetatable(Son,{__index=function (t,k)
return search(k,parent)
end})
end
function Son:new()
local Obj = {}
createClass()
setmetatable(Obj,{__index=Son})
return Obj
end
function Son:getState()
-- body
print("Son:getState")
end
return Son
调用
ocal Father = require("Father.lua")
f1=Father:new()
f1:getHeight()
local Monther = require("MOnther.lua")
m1=Monther:new()
-- m1:getHeight()
local Son = require("Son.lua")
s1=Son:new()
s1:getState()
s1:getHeight()
s1:getMoney()
实现单例
OtherAnimal = {}
OtherAnimal_mt={__index=OtherAnimal}
function OtherAnimal:new()
-- body
local Obj = {}
setmetatable(Obj,OtherAnimal_mt)
return Obj
end
function OtherAnimal:func1()
-- body
print("func1")
end
require("OtherAnimal.lua")
O2=OtherAnimal:new()
O2:func1()