The functions here are mainly used for callback functions. Reference: quick_cocos.
Xingyue's contribution ~~~
--[[-- 将lua对象及方法包装为一个匿名函数-- 许多功能需要传入一个 Lua 函数做参数,然后在特定事件发生时就会调用传入的函数。例如触摸事件、帧事件等等。-- example: local MyScene = class( "MyScene", function() ) return cc.Layer:create() end ) function MyScene:ctor() self.frameTimeCount = 0 -- 注册帧事件 self:addEventListener( cc.ENTER_FRAME_EVENT, self.onEnterFrame ) end function MyScene:onEnterFrame( dt ) self.frameTimeCout = self.frameTimeCount + dt end 上述代码执行时将出错,报告"Invalid self" ,这就是因为 C++ 无法识别 Lua 对象方法。 因此在调用我们传入的 self.onEnterFrame 方法时没有提供正确的参数。 要让上述的代码正常工作,就需要使用 handler() 进行一下包装: function MyScene:ctor() self.frameTimeCount = 0 -- 注册帧事件 self:addEventListener( cc.ENTER_FRAME_EVENT , handler( self, self.onEnterFrame ) ) end 实际上,除了 C++ 回调 Lua 函数之外,在其他所有需要回调的地方都可以使用 handler()。-- @param obj lua对象-- @param function method 对象方法-- @return function--]]function handler( obj, method ) return function(...) return method( obj, ... ) endend
A Simple Chat ~ (Xiao Bai: chatting about wool. You think everyone is free to talk about it like you ...)
function handler( obj, method ) return function(...) return method( obj, ... ) endendlocal Music = {}function Music:test( str ) print( "Music: " .. str )endlocal t = handler( Music, Music.test )t( "小白:星月是帅哥;星月:小白就是坦诚~~~" )输出:Music: 小白:星月是帅哥;星月:小白就是坦诚~~~
Handler returns a function, which is assigned to T. When the function T is called, the Music method test (STR) is called, so the above output is displayed.
What is the principle of T function call? (Xiao Bai: No one forces you to say it ~~~)
t( "小白:星月是帅哥;星月:小白就是坦诚~~~" )展开后就是:method( obj, "小白:星月是帅哥;星月:小白就是坦诚~~~" )method就是:Music.test。obj就是:Music。所以,替换后就是:Music.test( Music, "小白:星月是帅哥;星月:小白就是坦诚~~~" )Music找到函数test,因为用的是 “.” 点号调用函数,所以第一个参数就是self,第二个参数才是test方法里面的str。
Everyone understands it (Xiao Bai: No ~~~)
The content of this chapter ends here and I hope it will be useful to you ~
(TOM: Wait. I haven't figured it out ...)
The author uses cocos2d-x 3.0 + Lua learning and work experience, without the author's consent, please do not reprint! Thank you for your patience ~~~
This article is not approved by the author and cannot be reproduced. Otherwise, relevant responsibilities will be held accountable. For more information, see the source !!~~
Address: http://www.cnblogs.com/wodehao0808/p/4017210.html
(Original) cocos2d-x 3.0 + Lua learning and working (4): common functions (4): Handler