惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
I
InfoQ
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
量子位
博客园 - 叶小钗
月光博客
月光博客
IT之家
IT之家
G
Google Developers Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享

博客园 - 毛尹航

GAMES202课程资源 游戏设计制作配置表原则 Unity中文字和图片混合 UI仔需要了解的坑 遇到大段ifelse不要慌,先分层让条件正交 NGUI文字破碎 写一个可以用的Lua打印Table的函数 关于C#的接口的碎碎念 C#中接口是值类型还是引用类型? Unity3d笔试题大全 FPSCalc——简单FPS观测类 GameObjectPool——Unity中的对象池 MonoSingleton——Unity中的单例模式 用非递归、不用栈的方法,实现原位(in-place)的快速排序 一道有序洗牌的笔试题,阿里\UC等都用过 - 毛尹航 - 博客园 MFC中显示图像的放大、缩小、移动功能 MFC中设置对话框/窗体大小固定 MFC【5】MFC集合类 MFC【6】文件I/O和串行化
一个可以用的Lua的Class函数
毛尹航 · 2021-07-08 · via 博客园 - 毛尹航
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给它跳过去吧”,那可真实吃屎难忘拉屎人啊。