In what situation should i use coroutines?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Using coroutines properly

  2. What is the issue? No problems

  3. What solutions have you tried so far? Nothing

1 Like

coroutines run the code under it in a seperate thread thus aynchronously allowing other code to run. This is useful when you don’t want to wait for a code block to complete and prevent yieldinv.

1 Like

All code is actually already in a coroutine, you just don’t need to think about it most of the time.

For example, wait() pauses the current thread (with coroutine.yield) and tells the task scheduler to resume (coroutine.resume) the current thread after the specified amount of time.

The current thread’s state is saved somewhere, to be loaded when the thread is resumed.

Nothing is actually running “at the same time” as any other code; only one coroutine may be running at once. When a coroutine ends or yields, it is ended or put off and any other work that needs to be done is resumed.

By contrast, a wait() that does not use coroutines would just spin around doing nothing until its time has come:

local deadline = os.clock() + 5
repeat until os.clock() >= deadline

This would prevent anything else from running until five seconds have passed, because it does not hand-off execution to anything else.

As for what you should use it for - I can’t think of any situations right now that either can’t be solved with Event:Wait() or aren’t really applicable to common Roblox situations (like parsers/tokenizers)

3 Likes