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
原文地址:https://www.cnblogs.com/hackerl/p/8710181.html