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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM