-- @作者: baidwwy
local _Class = {}--保存父类
local function __Call(t, ... )--免".new"
return t.new(...)
end
local function _Create(self,ct,...)--构造函数
for i,v in ipairs(ct.super) do
_Create(self,v,...)--继承属性
end
if ct.ctor then ct.ctor(self,...) end
end
local function _RunSuper(t ,... )--运行父函数
return _Class[t.t][t.k](t.obj,...)
end
local _GetSuper = setmetatable({}, {__index=function (t,k)
if _Class[t.t][k] then--获取父函数
t.k = k
return _RunSuper
end
end})
function class(...)
local ct = {ctor=false,super={...}}--new的对象
_Class[ct] = {}--类函数实际保存
ct.new = function(...)
local ctor = {}
setmetatable(ctor,{ __index = function (t,k)
if _Class[k] then
_GetSuper.obj,_GetSuper.t = t,k--对象,父类
return _GetSuper
end
return _Class[ct][k]
end})
_Create(ctor,ct,...)--递归所有父类
return ctor
end
if #ct.super > 0 then--继承函数
setmetatable(_Class[ct],{__index = function (t,k)
for i,v in ipairs(ct.super) do
local ret = _Class[v][k]
if ret then return ret end
end
end})
end
return setmetatable(ct,{__newindex=_Class[ct],__call=__Call})
end
现在,我们来看看怎么使用:
base_type=class() -- 定义一个基类 base_type function base_type:ctor(x) -- 定义 base_type 的构造函数 print("base_type ctor") self.x=x end function base_type:print_x() -- 定义一个成员函数 base_type:print_x print(self.x) end function base_type:hello() -- 定义另一个成员函数 base_type:hello print("hello base_type") end
以上是基本的 class 定义的语法,完全兼容 lua 的编程习惯。我增加了一个叫做 ctor 的词,作为构造函数的名字。
下面看看怎样继承:
test=class(base_type) -- 定义一个类 test 继承于 base_type function test:ctor() -- 定义 test 的构造函数 print("test ctor") end function test:hello() -- 重载 base_type:hello 为 test:hello print("hello test") end
现在可以试一下了:
a=test.new(1) -- 输出两行,base_type ctor 和 test ctor 。这个对象被正确的构造了。 a:print_x() -- 输出 1 ,这个是基类 base_type 中的成员函数。 a:hello() -- 输出 hello test ,这个函数被重载了。