Lua 实现继承的一种方式

以下代码来自Loxodon Framework,截取自其中的一段

lua 复制代码
function class(classname, super)
    local cls = {}
    cls.__classname = classname
    cls.__class = cls

    cls.base = function (self)
        return cls.super
    end

    cls.__type = 0
    cls.super = super
    cls.__index = cls

    if super then
        setmetatable(cls,{__index = super, __call = function (t,...)
            local instance = setmetatable({},t)  
            instance:ctor(...)
            return instance
        end})
    else
        cls.ctor = function (...)
            
        end

        setmetatable(cls,{__call = function (t,...)
            local instance = setmetatable({},t)
            instance:ctor(...)
            return instance
        end})
    end

    if not cls.ctor then
        cls.ctor = function (...)   --构造函数
            
        end
    end

    return cls
end

调用方式

lua 复制代码
local t = {1,2,3}
t.age = 10

local a = class("a",t)
print(a.age)  --输出10

local b = a()   --调用了__call元方法,相当于是构造函数
print(b.age)  --输出10

当调用a.age时,a相当于cls,会从__index中寻找age,即super,也就是t中寻找

而当通过local b = a() 的方式调用时,会进入到__call元方法中,instance 会从cls继承,相当于把cls设置为了instance的元表,最终返回instance

相关推荐
钢铁男儿17 分钟前
Python 正则表达式实战:解析系统登录与进程信息
开发语言·python·正则表达式
野生技术架构师38 分钟前
2025年中高级后端开发Java岗八股文最新开源
java·开发语言
静若繁花_jingjing1 小时前
JVM常量池
java·开发语言·jvm
彷徨而立2 小时前
【C++】 using声明 与 using指示
开发语言·c++
@半良人2 小时前
Deepseek+python自动生成禅道测试用例
开发语言·python·测试用例
一只鲲2 小时前
48 C++ STL模板库17-容器9-关联容器-映射(map)多重映射(multimap)
开发语言·c++
ankleless4 小时前
Python 数据可视化:Matplotlib 与 Seaborn 实战
开发语言·python
Gavin_9154 小时前
一文速通Ruby语法
开发语言·ruby
搞一搞汽车电子4 小时前
vs studio 2017项目不支持studio vs2022
开发语言
witkey_ak98964 小时前
python 可迭代对象相关知识点
开发语言·python