cocos2dx-lua function.lua 定義了class方法,讓lua實現繼承像傳統語言一樣漂亮和方便
看定義
function class(classname, super) local superType = type(super) local cls --如果父類既不是函數也不是table則說明父類為空 if superType ~= "function" and superType ~= "table" then superType = nil super = nil end --如果父類的類型是函數或者是C對象 if superType == "function" or (super and super.__ctype == 1) then -- inherited from native C++ Object cls = {} --如果父類是表則復制成員並且設置這個類的繼承信息 --如果是函數類型則設置構造方法並且設置ctor函數 if superType == "table" then -- copy fields from super for k,v in pairs(super) do cls[k] = v end cls.__create = super.__create cls.super = super else cls.__create = super cls.ctor = function() end end --設置類型的名稱 cls.__cname = classname cls.__ctype = 1 --定義該類型的創建實例的函數為基類的構造函數后復制到子類實例 --並且調用子數的ctor方法 function cls.new(...) local instance = cls.__create(...) -- copy fields from class to native object for k,v in pairs(cls) do instance[k] = v end instance.class = cls instance:ctor(...) return instance end else --如果是繼承自普通的lua表,則設置一下原型,並且構造實例后也會調用ctor方法 -- inherited from Lua Object if super then cls = {} setmetatable(cls, {__index = super}) cls.super = super else cls = {ctor = function() end} end cls.__cname = classname cls.__ctype = 2 -- lua cls.__index = cls function cls.new(...) local instance = setmetatable({}, cls) instance.class = cls instance:ctor(...) return instance end end return cls end
寫個測試代碼,注意出錯的部分
local Base = class('Base') Base.__index = Base function Base:ctor(id) print('Base:ctor',id) self.id = id end local ExtBase = class('ExtBase',Base) ExtBase.__index = ExtBase function ExtBase:ctor(id) --Base:ctor(id) super(self,id) print('ExtBase:ctor',id) end
受傳統語言影響,會在子類調用基類的構造函數,而事實上,這導致直接將類型本身作為對象實例傳入
導致self指向是那個類型本身(也是個table)
那就只能這么寫了
Base.ctor(self,id)
有點丑了樣,封裝一下super函數,看起來好看一點。。
function super(o,...) --if (o and o.super and o.super.ctor) then o.super.ctor(o,...) --end end
