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 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12318 小时前
matlab画图工具
开发语言·matlab
dustcell.18 小时前
haproxy七层代理
java·开发语言·前端
norlan_jame18 小时前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone18 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ40220549619 小时前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月19 小时前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_5312371719 小时前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian19 小时前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡20 小时前
简单工厂模式
开发语言·算法·c#