-- ***** Class Manager 类管理*****‘local ClassManager ={}local this = ClassManager
function ClassManager.Class(className,...)print('ClassManager::Class')--print(className)-- 构建类local cls ={__className = className}--print(cls)-- 父类集合local supers ={...}for _, super inpairs(supers)do-- 获取父类的类型local superType =type(super)--print(superType)assert(superType ==nilor superType =='table'or superType =='function',
string.format("class() - create class \"%s\" with invalid super class type \"%s\"",
className, superType))if superType =='function'thenassert(cls.__create ==nil, string.format("class() - create class \"%s\" with more than one creating function",
className))
cls.__create = super
elseif superType =='table'thenif super['.isclass']thenassert(cls.__create ==nil,
string.format("class() - create class \"%s\" with more than one creating function or native class",
className));
cls.__create =function() super:create()endelse-- 用来保存父类
cls.__supers = cls.__supers or{}local dp =falsefor _, v inpairs(cls.__supers)doif v.__className == super.__className then
dp =truebreakendend-- set first super pure lua class as class.superifnot dp then-- 将父类中所有的对象(变量或者函数)拷贝到子类中
cls.__supers[#cls.__supers +1]= super
ifnot cls.super then
cls.super = super
endendendelseerror(string.format("class() - create class \"%s\" with invalid super type",
className),0)endend
cls.__index = cls
ifnot cls.__supers or#cls.__supers ==1thensetmetatable(cls,{__index = cls.super})else-- 设置cls的元表为supers中的父类setmetatable(cls,{__index =function(_, key)local supers = cls.__supers
for i=1,#supers dolocal super = supers[i]if super[key]thenreturn super[key]endendend})end-- 添加默认构造函数ifnot cls.constructor then
cls.constructor =function()endend-- new 方法构建类对象
cls.new =function(...)-- 构建一个对象local instance
if cls.__create then
instance = cls.__create(...)else
instance ={}end-- 设置对象的元表为当前类setmetatable(instance, cls)
instance.class = cls
instance:constructor(...)return instance
end
cls.create =function(_,...)return cls.new(...)end-- 返回类return cls
endlocal setmetatableindex =function(t, index)local mt =getmetatable(t)
mt = mt or{}ifnot mt.__index then
mt.__index = index
setmetatable(t, mt)elseif mt.__index ~= index thensetmetatableindex(mt, index)endendreturn ClassManager