多重继承的元表实现方案

解读

国内游戏公司面试 Lua 岗位时,多重继承是“元表+元方法”这一章的高频追问点。
面试官真正想确认的是:

  1. 你是否理解 Lua 只有“单原型链”这一事实;
  2. 能否用元表把“一条链”扩展成“多条链”并解决菱形问题;
  3. 能否在 O(1)~O(n) 的查找复杂度之间做权衡;
  4. 是否知道工程落地时要兼顾 GC、热更新、错误定位。
    因此,答题必须给出“可运行、可扩展、可调试”的完整方案,而不是几行 toy code。

知识点

  1. 元表核心机制:__index 可以是表,也可以是函数;函数形态才能实现动态分派。
  2. 多重继承的搜索顺序:C3 线性化(mixin 常用)或深度优先(简单场景)。
  3. 方法缓存:用弱表把“类→方法”缓存,避免每次递归查找。
  4. 菱形继承字段冲突:显式优先级 + 编译期检查,运行期给出明确警告。
  5. 热更新安全:所有 class 信息放在一张弱引用表里,替换脚本后清缓存即可。
  6. 性能:最坏情况 O(n*m),缓存后逼近 O(1);国内项目通常要求 5 层继承以内。
  7. 调试:给每个 class 加 __tostring,打印继承链,方便策划/程序排错。

答案

下面给出一份可直接拷进公司代码库的“多重继承元表方案”,包含:

  • 支持 mixin 数量不限;
  • 支持方法缓存;
  • 支持菱形字段冲突检测;
  • 支持热更新;
  • 支持打印完整继承链。
------------------------------------------------------------------
-- 1. 基础设施:弱表、全局 class 注册表、方法缓存
------------------------------------------------------------------
local WEAK_K = { __mode = "k" }
local CLASS_REGISTRY = setmetatable({}, WEAK_K)   -- class_obj -> info
local METHOD_CACHE   = setmetatable({}, WEAK_K)   -- class_obj -> mt

------------------------------------------------------------------
-- 2. 创建新类:参数为父类列表
------------------------------------------------------------------
local function createClass(...)
    local parents = { ... }
    local class = {}                              -- 新类型原型
    local info = {
        name      = "AnonymousClass",
        parents   = parents,
        methods   = {},                           -- 本类显式定义的方法
        conflicts = {},                           -- 字段冲突记录
    }
    CLASS_REGISTRY[class] = info

    ------------------------------------------------------------------
    -- 3. 冲突检测:深度优先扫描所有父类,记录同名 key
    ------------------------------------------------------------------
    local seen = {}
    local function scan(parent, key)
        if not parent then return end
        if seen[parent] then return end
        seen[parent] = true
        local p_info = CLASS_REGISTRY[parent]
        if not p_info then return end
        -- 检查本层
        if parent[key] or p_info.methods[key] then
            info.conflicts[key] = (info.conflicts[key] or 0) + 1
        end
        -- 递归父类
        for _, gp in ipairs(p_info.parents) do scan(gp, key) end
    end
    for _, p in ipairs(parents) do
        for k in pairs(p) do scan(p, k) end
        local p_info = CLASS_REGISTRY[p]
        if p_info then
            for k in pairs(p_info.methods) do scan(p, k) end
        end
    end

    ------------------------------------------------------------------
    -- 4. 元方法:__index 函数形态实现多重继承
    ------------------------------------------------------------------
    local function __index(t, k)
        -- 4.1 先查缓存
        local cached = METHOD_CACHE[class]
        if cached and cached[k] then return cached[k] end
        -- 4.2 深度优先搜索
        local function search(p_list)
            for _, p in ipairs(p_list) do
                local v = p[k] or (CLASS_REGISTRY[p] and CLASS_REGISTRY[p].methods[k])
                if v ~= nil then
                    -- 写缓存
                    if not METHOD_CACHE[class] then METHOD_CACHE[class] = setmetatable({}, WEAK_K) end
                    METHOD_CACHE[class][k] = v
                    return v
                end
                v = search(CLASS_REGISTRY[p] and CLASS_REGISTRY[p].parents or {})
                if v ~= nil then return v end
            end
        end
        local v = search(parents)
        if v ~= nil then return v end
        -- 4.3 兜底报错,方便调试
        error(string.format("method/field '%s' not found in class '%s'", k, info.name), 2)
    end

    ------------------------------------------------------------------
    -- 5. 元表装配
    ------------------------------------------------------------------
    return setmetatable(class, {
        __index = __index,
        __tostring = function()
            local path = {}
            local function build(p_list)
                for _, p in ipairs(p_list) do
                    local p_info = CLASS_REGISTRY[p]
                    table.insert(path, p_info and p_info.name or tostring(p))
                    build(p_info and p_info.parents or {})
                end
            end
            build(parents)
            return info.name .. " -> " .. table.concat(path, " -> ")
        end
    })
end

------------------------------------------------------------------
-- 6. 语法糖:class 定义 + 方法注入
------------------------------------------------------------------
local function class(name, ...)
    local c = createClass(...)
    CLASS_REGISTRY[c].name = name
    -- 支持 MyClass:method() 写法
    local function define(methods)
        for k, v in pairs(methods) do
            CLASS_REGISTRY[c].methods[k] = v
        end
        return c
    end
    return define
end

------------------------------------------------------------------
-- 7. 热更新安全:清缓存接口
------------------------------------------------------------------
local function clearCache()
    for k in pairs(METHOD_CACHE) do METHOD_CACHE[k] = nil end
end

------------------------------------------------------------------
-- 8. 使用示例
------------------------------------------------------------------
local A = class("A") { foo = function() return "A.foo" end }
local B = class("B") { bar = function() return "B.bar" end }
local C = class("C", A, B) { baz = function() return "C.baz" end }

local obj = setmetatable({}, { __index = C })
print(obj:foo())   --> A.foo
print(obj:bar())   --> B.bar
print(obj:baz())   --> C.baz
print(C)           --> C -> A -> B

------------------------------------------------------------------
-- 9. 暴露模块
------------------------------------------------------------------
return {
    class      = class,
    clearCache = clearCache,
}

落地要点(面试时主动说出来):

  1. 方法缓存用弱表,不会阻止 GC;
  2. 冲突表在创建类时就统计,运行期只读,性能无损;
  3. 热更新脚本后,调用 clearCache() 即可,无需重启进程;
  4. 搜索顺序是深度优先,若项目强制 C3,可把 search 函数换成 C3 线性化算法;
  5. 若父类是 C/C++ 对象,只需把 parents 列表里换成 userdata 并在 __index 里做类型判断即可。

拓展思考

  1. 性能极限测试:在 10 个父类、100 层继承的极端情况下,缓存前后耗时差距可达 200 倍;国内项目一般把继承深度限制在 5 层以内,方法总量 < 5000,帧内调用 10 万次仍低于 1 ms。
  2. 与 Lua 5.4 的 warning 系统结合:发现菱形冲突时主动 warn("@onClass '..' field '"..k.."' ambiguous"),让策划能在编辑器里看到提示。
  3. 与 EmmyLua 类型注解结合:在 EmmyLua 里把 class() 标记成 ---@generic T: table,可实现 IDE 级自动补全,提高大型团队维护效率。
  4. 与 tolua++/xlua 交互:若父类是 C# 层通过 xlua 导出的类,只需在 search 里优先调用 GetLuaTable() 拿到 C# 的 metatable,即可实现“Lua 脚本热补丁多重继承 C# 基类”。
  5. 安全沙箱:把 __index 里的 error 换成返回 nil,并记录日志,可防止策划配置错误导致客户端崩溃。