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

相关推荐
charlie11451419111 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
神仙别闹19 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
尘世闲鱼3 小时前
解数独(C++版本)
开发语言·c++·算法·解数独
纨妙4 小时前
python打卡day59
开发语言·python
wuxuanok4 小时前
Web后端开发-请求响应
java·开发语言·笔记·学习
Sally璐璐4 小时前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
像风一样的男人@4 小时前
python --货车装厢问题
开发语言·python
Humbunklung4 小时前
Rust枚举:让数据类型告别单调乏味
开发语言·后端·rust
Y1nhl4 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展