在網上看到這樣一段代碼,真是誤人子弟呀,具體就是:
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