此模块的文档可以在Module:Class/doc创建
local C = {}
C.classMeta = {
__call = function(cls, ...)
local instance = {}
setmetatable(instance, cls)
return instance:_init(...)
end,
}
C.new = C.classMeta.__call
function C.createClassBy(metatable)
return function(definition)
definition.__index = definition
setmetatable(definition, metatable)
return definition
end
end
C.class = C.createClassBy(C.classMeta)
function C.derive(...)
-- "cls" is the new class
local cls, bases = {}, { ... }
-- copy base class contents into the new class
for i, base in ipairs(bases) do
for k, v in pairs(base) do
cls[k] = v
end
end
-- set the class's __index, and start filling an "instanceOf" table that contains this class and all of its bases
-- so you can do an "instance of" check using my_instance.instanceOf[MyClass]
cls.__index, cls.instanceOf = cls, { [cls] = true }
for i, base in ipairs(bases) do
for c in pairs(base.instanceOf) do
cls.instanceOf[c] = true
end
cls.instanceOf[base] = true
end
-- the class's __call metamethod
-- return the new class table, that's ready to fill with methods
return class(cls)
end
return C