1. 程式人生 > >cocos2dx-lua class

cocos2dx-lua class

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