Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How to stop a coroutine (Or using another alternative)?

Asked by 4 years ago

I am trying to make a tool which actions such as reloading are executed via coroutines. When the player unequips the tool, the coroutine will stop and the action will be discarded.

The biggest issue about coroutines is there's no way to stop them outside the code. Is there any way to make a piece of code that can be stopped or resumed whenever you want? (something like threads)

0
Coroutine.yeild JesseSong 3916 — 4y

1 answer

Log in to vote
2
Answered by
Sulfone 141
4 years ago

To better understand it, it may be useful to know how a Roblox-style wait could be implemented: Calling the wait could give the current coroutine to the scheduler with a resume. The wait function would then call coroutine.yield. The scheduler's job will be to resume the given coroutine at the correct time.

I haven't found a way of removing coroutines from Roblox's scheduler or otherwise reliably cancelling waits. But worry not, a workaround is to replacing use of wait with use of a custom wait function.

One way would be to define a custom wait that waits normally first, and then calls coroutine.yield if it's supposed to be stopped. With nothing left to resume it (unless you decide to resume it yourself later for some reason), the coroutine would be stopped at that point. Tracking whether a coroutine should be killed could be done with a weak coroutine-key table, or just a variable.

Another way would be to entirely use a custom scheduler that supports cancelling, replacing Roblox's waits with theirs. Two examples I've been told are Roblox-compatible (although I haven't tried them) are minisched by TerrodactyI and eztask by ShoesForClues. If you want to, you could even entirely make your own one!

Ad

Answer this question