一个可以用的Lua的Class函数
function SetMetaTableIndex(t, index)
if t == nil or index == nil then
---error
return
end
local mt = getmetatable(t)
if not mt then
mt = {}
end
if not mt.__index then
mt.__index = index
setmetatable(t, mt)
elseif mt.__index ~= index then
SetMetaTableIndex(mt, index)
end
end
function Class(classname, ...)
local cls = { __cname = classname }
local supers = { ... }
for _, super in ipairs(supers) do
if type(super) == "table" then
cls.__supers = cls.__supers or {}
cls.__supers[#cls.__supers + 1] = super
if not cls.super then
cls.super = super
end
else
---error
return
end
end
cls.__index = cls
if not cls.__supers or #cls.__supers == 1 then
setmetatable(cls, { __index = cls.super })
else
setmetatable(cls, { __index = function(_, key)
local supers = cls.__supers
for i = 1, #supers do
local super = supers[i]
if super[key] then
return super[key]
end
end
end })
end
if not cls.Ctor then
cls.Ctor = function()
end
end
cls.New = function(...)
local instance = {}
SetMetaTableIndex(instance, cls)
instance.class = cls
instance:Ctor(...)
return instance
end
return cls
end
看过很多Lua的Class函数,有些就是扩展的太多了,比如我看过一个tolua版本的Class函数甚至还会支持继承UserData,牛逼,但真的不推荐,维护起来像屎一样。
基础函数因为会和所工作平台的逻辑耦合,会出现很多诡异的问题,也会出现“因为是之前的屎当时没出问题我们没敢动所以if else给它跳过去吧”,那可真实吃屎难忘拉屎人啊。
浙公网安备 33010602011771号