Run function in context of another script

Hi!

So, I have a timer module in my project. The problem I’m facing is the fact that the timer callback gets called in the context of the script instance that called the timer’s update() function, not in the context of the script instance that registered the timer.

I think on the native side, you can do dmScript::getInstance() and dmScript::setInstance(). Would setting __dm_script_instance__ on the global object from the Lua side, then setting it back have the same effect or is there potential for wacky stuff happening? (lost reference counts or that kind of stuff)

In my specific use-case I need pause-able timers, which would either require me to implement this on top of @britzl’s defold-timer, which after quickly glancing over the code seems to save the instance properly, or modify defold-timer to suit my needs. Either way, it would have been cool to have a pure Lua solution.

UPDATE: The __dm_script_instance__ approach seems to work so I might use it temporarily, but I have no idea if it won’t break other things in subtle ways.

3 Likes

Wow, that’s some interesting research. I didn’t expect that storing and changing the script instance would work. Let me know if you find any issues with that approach!

1 Like

Yes, great digging! It will probably work fine for the most part. I think the only problem with your approach is accessing internals which are not part of the API, but you seem aware of that. Otherwise, I would try to delete the different instances before the callback is called to make sure nothing is dangling.