Is it possible to setup callback on a different script?

I’m using websocket extension along with colyseus library. Sometimes I need to keep the connected room which created from a script and reuse it in another script. I tried many ways but it seems impossible. Looks like the setup callback API only accept if the callback function is the same script context with the room variable.
ERROR:WEBSOCKET: Failed to setup callback

I don’t want to close and recreate the connection.
Is there a way to change the variable’s context to the current script? Or allow to setup callback on a different script?

I think the root cause is that the script instance which the room variarble original created was disposed. By moving the room connection code to a longer-alive script, the setup callback issue gone but the new issue is I can’t get gui nodes in current script inside room listeners. I think changing script context for listeners might help

I don’t know the specifics of your code, but in general you need to think about which script that is calling an asynchronous function and how the callback is invoked. Is the script still alive when you get the callback or has it been deleted? Also, if you are using coroutines to wait for the result you need to pay attention to how the coroutine is resumed. You can get and set the script instance context and use that to change in which context some code is called, but it is a bit hacky to do so. I did it in this Tic Tac Toe example, but I’ve been meaning to refactor the code to not have to do it: https://github.com/defold/game-xoxo/blob/main/xoxo/script/src/script.cpp

My project structure is kind of this:

Main collection
— ScreenA collection
— ScreenB collection

The seriano is:
1/ At ScreenA, create a connection using Colyseus over websocket extension, keep the connection instance in a lua module
2/ Switch to ScreenB (remove ScreenA), get and reuse the connection → Failed

My current solution is:
1/ At ScreenA, change script context to Main, create a connection using Colyseus over websocket extension, revert script context to ScreenA.
2/ Switch to ScreenB (remove ScreenA), get and reuse the connection → Success (but the room callbacks sticks with Main script context, I must change script context to ScreenB for every room callbacks)

Yes, looks like it’s the only way and since I’m using Event library of Insality, it has the same function as in your script

1 Like