lua简单实现一个类

众所周知lua是没有类的概念

但是为了方便开发,可以使用table实现一个class

看了下lua pureMVC的class实现

因为是在工程中使用,写了很多关于安全的代码

其实跟class本身的特性无关

class的功能无非是:派生,继承

所以实现这两个就行了

另外安利一下VS code里的插件luaide

确实挺好用的,才一百块钱买断

function class(className,...)
    local l_table = {name=className}

    l_table.supers={...}

    --继承实现
    setmetatable(l_table,{__index=function(_,v)
        local l_sp = l_table.supers
        for i=1,#l_sp do
            if l_sp[i][v] then
                return l_sp[i][v]
            end
        end
    end})
    
    --派生实现
    l_table.new = function(...)
        local l_instance
        l_instance = {}
        inherit(l_instance,l_table)

        return l_instance
    end

    return l_table
end

inherit=function(derived,super)
    local l_mt = getmetatable(derived)
    if not l_mt then
        l_mt = {}
    end
    if not l_mt.__index then
        l_mt.__index = super
        setmetatable(derived,l_mt)
    elseif l_mt.__index ~= super then
        inherit(l_mt,super)
    end
end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值