cocos2dx lua中使用class實現繼承api中的類
阿新 • • 發佈:2019-02-09
如果需要擴充套件api中的類時,使用繼承的方式,需要重寫的就重寫,需要擴充套件就擴充套件
直接上程式碼,程式碼中有解釋
require "extern" --使用class方法需要的extern.lua模組 --呼叫父類方法 function getSuperMethod(table, methodName) local mt = getmetatable(table) local method = nil while mt and not method do method = mt[methodName] if not method then local index = mt.__index if index and type(index) == "function" then method = index(mt, methodName) elseif index and type(index) == "table" then method = index[methodName] end end mt = getmetatable(mt) end return method end --自定義類繼承sprite,前提是這個sprite必須先繫結好c++中的sprite MyCustom = class("MyCustom",function(filename) --通過返回一個sprite實現繼承sprite類, return cc.Sprite:create(filename) --這裡的function就是下面的MyCustom.new end) MyCustom.__index = MyCustom --索引訪問 MyCustom.aaa = 0 --定義屬性及對應值 function MyCustom:create(filename , aaa) local mySpr = MyCustom.new(filename) --這裡使用的是''.",不是":" self.aaa = aaa --設定屬性值 return mySpr end -- 實現重寫父類方法 function MyCustom:setVisible(visible) getSuperMethod(self, "setVisible")(self, visible) --呼叫父類方法並傳遞引數 print("override setVisible method") end