SoFunction
Updated on 2025-04-11

Solution to make callback function support callback object method in Lua

In Cocos2d-Lua, there are many asynchronous or delayed operations, such as loading pictures in the background, waiting for a certain period of time to execute code, etc. Functions of these functions usually require a function to be passed as a parameter.


Copy the codeThe code is as follows:

-- Load an image in the background and output a message after the loading is completed
("", function()
    print("load completed")
end)


But it would be a little difficult if we want this callback to support an object method. Because Lua's object method needs to use the object:method() form when calling, the callback cannot support this format.

Fortunately, Lua's powerful closure function is not only easy to use but also has no impact on performance, so we can rewrite the code to:


Copy the codeThe code is as follows:

local MyClass = class("MyClass")

function MyClass:print()
    print("load completed")
end

----

local my = ()

("", function()
    my:print()
end)


The principle is very simple, it is just to call object methods in an anonymous function.

The Quick framework has provided a simpler method of using the handler() function:


Copy the codeThe code is as follows:

("", hander(my, ))