要求:
- 模仿C++类的行为
- 实现 a = A()
- 类的复制实现深拷贝
- 实现构造函数
- 只考虑单继承,多继承实现在lua程序设计中有提及,但是个人认为在lua中使用多继承会不会不太合适。
local function class(...) --只考虑单继承
local tmpClass = {
classType = 'class',
_ctor = function () end
}
local mt = {}
for key, value in pairs({...}) do
if value.classType == 'class' and type(value) == 'table' then --处理父类
mt.__index = value
elseif type(value) == 'table' then --处理自定义的类
for iKey, iValue in pairs(value) do
if iKey == '_ctor' then --构造函数
local ctor = iValue
mt.__call = function (self,...) --返回一个构造好的class
local newClass = class(self)
ctor(newClass,...)
return newClass
end
else
tmpClass[tostring(iKey)] = iValue
end
end
end
end
setmetatable(tmpClass,mt)
return tmpClass
end
return class