local _, _, majorv, minorv, rev = string.find(_VERSION, "(%d).(%d)[.]?([%d]?)")
local VersionNumber = tonumber(majorv) * 100 + tonumber(minorv) * 10 + (((string.len(rev) == 0) and 0) or tonumber(rev))

function setmt__gc(t, mt)
    if VersionNumber == 510 then
        local prox = newproxy(true);
        getmetatable(prox).__gc = function()
            mt.__gc(t);
        end
        t[prox] = true;
    end
    return setmetatable(t, mt);
end

--递归构造基类
function _ctorclass(cls, obj, tbUniqClassSet, ...)
    if tbUniqClassSet[cls.__cname] ~= nil then
        return;
    end
    tbUniqClassSet[cls.__cname] = true;

    if cls.superClss ~= nil then
        local superCount = #cls.superClss;
        for i = 1, superCount do
            local s = cls.superClss[i];
            _ctorclass(s, obj, tbUniqClassSet, ...);
        end
    end
    cls.ctor(obj, ...);
end

function ctorclass(obj, ...)
    if obj ~= nil then
        local tbUniqClassSet = {}
        _ctorclass(obj.class, obj, tbUniqClassSet, ...);
    end
end

--递归析构基类
function _dctorclass(cls, obj, tbUniqClassSet)
    if tbUniqClassSet[cls.__cname] ~= nil then
        return;
    end
    tbUniqClassSet[cls.__cname] = true;

    cls.dtor(obj);
    if cls.superClss ~= nil then
        local superCount = #cls.superClss;
        for i = 1, superCount do
            local s = cls.superClss[superCount - i + 1];
            _dctorclass(s, obj, tbUniqClassSet);
        end
    end
end

function dtorclass(obj)
    if obj ~= nil then
        local tbUniqClassSet = {}
        _dctorclass(obj.class, obj, tbUniqClassSet);
    end
end

function class(classname, ...)
    local cls = {};
    local superlist = {...};
    local supercount = table.getn(superlist);
    if supercount > 0  then --复制基类方法
        local clss_supers = {};
        local clss_super_byname = {};

        --单继承和多继承通用继承逻辑
        local i = 0;
        local supername = nil;
        for _, s in ipairs(superlist) do
            for k,v in pairs(s) do
                cls[k] = v;
            end;

            if i == 0 then
                supername = s.__cname;
            else
                supername = supername .. ",".. s.__cname;
            end
            i= i + 1;

            table.insert(clss_supers, s);
            clss_super_byname[s.__cname] = s;
        end

        cls.superClss = clss_supers;
        cls.superClsByName = clss_super_byname;
    else
        cls = {ctor = function() end, dtor = function() end};
    end

    cls.__cname = classname;
    cls.__index = cls
    cls.__gc = function(t)
        dtorclass(t);
    end

    function cls:new(...)
        --实例化
        local newtable = {};
        local instance = setmt__gc(newtable, cls);

        instance.class = cls;
        ctorclass(instance, ...);
        return instance;
    end

    return cls;
end
