cocos2dx lua中继承与覆盖C++方法
cocos2dx的extern.lua中的class方法为lua扩展了面向对象的功能,这使我们在开发中可以方便的继承原生类
但是用function返回对象的方法来继承C++类是没有super字段的,这使得在需要重写父类方法的时候没办法调用父类方法
在某位大神的博文中看到的代码
local _setVisible = nil local MyLayer = class("MyLayer", function() local layer = CCLayer:create() -- save c++ member method point. _setVisible = layer.setVisible return layer end) -- override CCLayer::setVisible function MyLayer:setVisible(visible) -- invoke CCLayer::setVisible _setVisible(self, visible) -- to do something. end return MyLayer
下面这种方法是在metatable中一层一层递归的找指定函数,比上面那种优美很多
local 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 local MyLayer = class("MyLayer", function() return CCLayer:create() end) -- override CCLayer::setVisible function MyLayer:setVisible(visible) -- invoke CCLayer::setVisible getSuperMethod(self, "setVisible")(self, visible) -- to do something. end return MyLayer在lua中继承cocos2dx的C++类还是有诸多不便的,有些时候用装饰者模式更好