Skip to content

Considerations for use

Juju Adams edited this page Dec 7, 2021 · 10 revisions

As with any library, there are some nuances to bear in mind. Coroutines, due to their asynchronous nature, are liable to be tricky to debug. They can also be overused, solving problems through over-engineered solutions. Here's our best guidance on what to do, and what to avoid, when using coroutines.

 

Do

Use oCoroutineManager

oCoroutineManager is a persistent object that you can find in the Coroutines folder when importing the library. Drag an instance of this object into the first room in your game and it'll take care of calling CoroutineEventHook() for you without you lifting a finger. However, be careful when you're using instance deactivation! If oCoroutineManager is deactivated then coroutines will fail to execute properly.

Keep an eye on syntax for two-part commands

It's easy to accidentally forget a THEN should come after a YIELD, and an END should match a WHILE. Whenever you type out two-part commands always finish writing the entire structure before filling in the details (inner function, condition etc). This will ensure you never introduce facepalm-worthy glitches into your code due to incorrect syntax.

Add ASYNC_TIMEOUT to everything that talks to a server

Whilst it's easier to assume that HTTP and TCP/UDP packets are going to time out by themselves, you're often not in control of the parameters of timeout behaviours. Additionally, occasionally connections won't timeout in a useful or controllable way and you'll need to implement your own anyway. Add custom timeouts where you can - it's a core feature for ASYNC_AWAIT_* commands for a reason.

 

Don't

Have two coroutines setting the same variable at the same time

It's really easy to end up with two coroutines arguing over what the "correct" value for a variable is if both coroutines are liable to try to set a variable at the same time. This can end up in a deadlock situation where coroutines never finish execution because neither coroutine can bring a variable to where it needs to be to get the coroutine to complete.

Modify arrays/structs whilst iterating over them using FOREACH...THEN

There's a note regarding this in the documentation for FOREACH...THEN but it bears re-stating: don't modify the data structure you're iterating over. It is going to break. Use a WHILE...THEN loop for dynamic data structures.

Overuse coroutines for very simple animations

It's tempting to use coroutines for everything, but they aren't free to run, and they do have an overhead. For really simple animations, always consider the obvious and crude approach of sticking something in a Step event. Coroutines are fun! Don't wear them out by using them too much.