In Cocos2d-lua, there are many asynchronous or deferred operations, such as background loading of pictures, waiting for a certain amount of time to execute code, and so on. Functions of these functions typically require the passing of a function as an argument.
Copy Code code as follows:
--load an image in the background, output message after loading completes
Display.addimageasync ("Hello.png", function ()
Print ("Load Hello.png completed")
End
But if we want this callback to support an object approach, it's a little difficult. Because the Lua object method needs to use the Object:method () Form when invoked, the callback cannot support this format.
The good news is that Lua's powerful closures are easy to use and have no impact on performance, so we can rewrite the code to:
Copy Code code as follows:
Local MyClass = Class ("MyClass")
function Myclass:print ()
Print ("Load Hello.png completed")
End
----
Local i = MyClass.New ()
Display.addimageasync ("Hello.png", function ()
My:print ()
End
The principle is very simple, is to invoke the object method in the anonymous function.
The quick framework already provides a simpler way to use the handler () function:
Copy Code code as follows:
Display.addimageasync ("Hello.png", hander (My, My.print))