A workaround for the callback function in Lua to support the callback object method _lua

Source: Internet
Author: User
Tags lua

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))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.