lua類的定義

2021-09-11 00:25:56 字數 1550 閱讀 1112

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

endif clsnames[classname] then

bxlog.e("has create the same name, "..classname)

return nil

endclsnames[classname] = true

local cls = nil

if basecls then

cls = basecls:create()

else

cls = {}

endcls.m_cn = classname

cls.getclassname = function(self)

local mcls = __getmetatable(self)

return mcls.m_cn

endcls.create = function(self, ...)

local newcls = {}

__setmetatable(newcls, self)

self.__index = self

newcls:__init(...)

return newcls

endreturn cls

end

這個**的邏輯:

1.建立乙個類,其實是建立了乙個父類的物件。

然後指定自己的create.

2.建立乙個類的物件,其實就是建立乙個表,這個表的元表設定為自己。然後呼叫初始化。

上面是錯誤的思路。

----------------------------------------

我的理解:

1.建立類:建立乙個表, 且__index指向父類。

2.建立物件:建立乙個表,元表設定為類。

### 就是這麼簡單,只要看下面的cls 和inst 兩個表就可以了。

我來重構,如下為核心**:

function class(classname, basecls)

local cls = {}

if basecls then

cls.__index = basecls

endfunction call(self, ... )

local inst = {}

inst.__index = self--靜態成員等。

setmetatable(inst, self)

inst:__init(...)

return inst

endcls.__call = call

return cls

end

lua 定義類 就是這麼簡單

在網上看到這樣一段 真是誤人子弟呀,具體就是 lua類的定義 如下 local clsnames local setmetatable setmetatable local getmetatable getmetatable function class classname,basecls if c...

Lua類的實現

cocos2dx中有關於lua類的實現,見cocos原始碼 framework functions。先講一部分比較難理解的 function class classname,super local cls inherited from lua object if super then cls set...

lua方法的定義 呼叫

冒號和點來定義個方法 當通過冒號定義方法的時候 預設傳乙個引數 self 而使用點定義的時候則不會傳遞乙個預設的self。使用冒號定義方法,可以使用點來呼叫,如果不顯式的把自身當做第乙個引數傳遞的話,那麼就會把第乙個引數當做自身賦值給self 引數就會少乙個。使用點定義的方法 也可以使用冒號呼叫,但...