lua类的定义

lua类的定义

代码如下:

复制代码

local clsNames = {}
local __setmetatable = setmetatable
local __getmetatable = getmetatable

function Class(className, baseCls)
    if className == nil then
        BXLog.e("className can't be nil")
        return nil
    end

    if clsNames[className] then
        BXLog.e("has create the same name, "..className)
        return nil
    end
    clsNames[className] = true
    
    local cls = nil
    if baseCls then
        cls = baseCls:create()
    else
        cls = {}
    end
    cls.m_cn = className

    cls.getClassName = function(self)
        local mcls = __getmetatable(self)
        return mcls.m_cn
    end

    cls.create = function(self, ...)
        local newCls = {}
        __setmetatable(newCls, self)
        self.__index = self
        newCls:__init(...)
        return newCls
    end

    return cls
end

复制代码

 

这个代码的逻辑:
1.创建一个类,其实是创建了一个父类的对象。
然后指定自己的create.

2.创建一个类的对象,其实就是创建一个表,这个表的元表设置为自己。然后调用初始化。

上面是错误的思路。
----------------------------------------

 

我的理解:
1.创建类:创建一个表, 且__index指向父类。

2.创建对象:创建一个表,元表设置为类。

### 就是这么简单,只要看下面的cls 和inst 两个表就可以了。

我来重构,如下为核心代码:

复制代码

function Class(className, baseCls)
    local cls = {}
    if baseCls then
        cls.__index = baseCls
    end

    function call(self, ... )
        local inst = {}
        inst.__index = self--静态成员等。
        setmetatable(inst, self)
        inst:__init(...)
        return inst
    end
    cls.__call = call

    return cls
end
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值