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

相关推荐
满天星830357714 分钟前
【C++】AVL树的模拟实现
开发语言·c++·算法·stl
weixin_4569042732 分钟前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
ss27335 分钟前
手写MyBatis第107弹:@MapperScan原理与SqlSessionTemplate线程安全机制
java·开发语言·后端·mybatis
麦麦鸡腿堡1 小时前
Java的动态绑定机制(重要)
java·开发语言·算法
时间之里1 小时前
【c++】:Lambda 表达式介绍和使用
开发语言·c++
Tiger_shl2 小时前
C# 预处理指令 (# 指令) 详解
开发语言·c#
@Kerry~2 小时前
phpstudy .htaccess 文件内容
java·开发语言·前端
CRMEB系统商城2 小时前
CRMEB多商户系统(PHP)v3.3正式发布,同城配送上线[特殊字符]
java·开发语言·小程序·php
sali-tec3 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
一壶浊酒..3 小时前
python 爬取百度图片
开发语言·python·百度