zoukankan      html  css  js  c++  java
  • 一个可以用的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给它跳过去吧”,那可真实吃屎难忘拉屎人啊。

  • 相关阅读:
    MVC传递数据的方式
    c#面向对象的多态
    使用扩展方法创建 HTML Helper
    了解视图、视图数据和 HTML Helper
    十种技能方法提高IT人薪酬
    ASP.net 2.0:系统优化
    第一个简单的MVC页面
    用户体验时代到来,功能不再重要
    关于SQL递归优化
    web(2)
  • 原文地址:https://www.cnblogs.com/fastcam/p/14987470.html
Copyright © 2011-2022 走看看