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

相关推荐
冷雨夜中漫步5 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
m0_736919107 小时前
C++代码风格检查工具
开发语言·c++·算法
2501_944934737 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖7 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472468 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ9 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024069 小时前
C++ 文件和流
开发语言
m0_706653239 小时前
分布式系统安全通信
开发语言·c++·算法
寻寻觅觅☆10 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx10 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列