通过lua的设置元表__index字段,巧妙的运用在无法索引到对象的key时会调用__index的机制,实现了伪多态、继承。
代码如下:
inheritance = {}
_classTotalTable = {}
function inheritance:class(father)
local classVo = {}
classVo.constructor = false --构造函数
classVo.father = father --父类
classVo.new = function(...)
local obj = {}
setmetatable(obj,{__index = _classTotalTable[classVo]})
local create
create = function(c,...)
if c.father then
create(c.father,...)
end
if c.constructor then
c.constructor(obj,...)
end
end
create(classVo,...)
return obj
end
local virtualTable = {}
-- tip:当经过此继承代码return的对象增加成员变量时,放入虚表
_classTotalTable[classVo] = virtualTable
setmetatable(classVo,{__newindex =
function(table,key,value)
virtualTable[key] = value
end
})
-- tip:索引不到对应key调用__index
-- 索引虚表,父类有此值,给予子类
if father then
setmetatable(virtualTable,{__index =
function (table,key)
local ret = _classTotalTable[father][key]
virtualTable[key] = ret
return ret
end
})
end
return classVo
end
--使用事例
baseClass = inheritance:class()
function baseClass:constructor()
print("base:constructor")
end
function baseClass:wowo()
print("base:wowo")
end
sonClass = inheritance:class(baseClass)
function sonClass:constructor()
print ("son:constructor")
end
function sonClass:wowo()
print("son:wowo")
end
newson = sonClass:new() --base:constructor --son:constructor
newson:wowo() --son:wowo