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

相关推荐
无限进步_15 分钟前
【C++】验证回文字符串:高效算法详解与优化
java·开发语言·c++·git·算法·github·visual studio
浅时光_c18 分钟前
12 指针
c语言·开发语言
charlie11451419122 分钟前
嵌入式现代C++工程实践——第10篇:HAL_GPIO_Init —— 把引脚配置告诉芯片的仪式
开发语言·c++·stm32·单片机·c
call me by ur name24 分钟前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
dog25024 分钟前
细看高维空间中距离度量失效
开发语言·php
码云数智-大飞26 分钟前
Rust的所有权模型如何消除内存安全问题?与C++的RAII有何异同?
开发语言
如意猴29 分钟前
【前端】002--怎样制作一个简历界面?
开发语言·前端·javascript
夜珀32 分钟前
OpenTiny NEXT 从入门到精通·第 6 篇
开发语言·前端框架
仍然.1 小时前
多线程---CAS,JUC组件和线程安全的集合类
java·开发语言
航Hang*1 小时前
VMware vSphere 云平台运维与管理基础——第5章:VMware vSphere 5.5 高级特性
运维·服务器·开发语言·windows·学习·虚拟化