From d08bb6dd106c5342176e1e77501cc100c42211ac Mon Sep 17 00:00:00 2001 From: DarkWiiPlayer Date: Thu, 20 Jul 2023 21:21:52 +0200 Subject: [PATCH] Add example to coroutines post --- Coroutines.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Coroutines.md b/Coroutines.md index 30c81c8..7cf4326 100644 --- a/Coroutines.md +++ b/Coroutines.md @@ -23,6 +23,38 @@ If we think of a normal function, the way it works is that we **call** the funct In a similar way, a very simple coroutine will do the same thing: We will **create** the coroutine, it will **execute** and at some point it will end and (implicitly) **yield** back to the calling code. +Here is a simple example of how this looks in practice. + +First we define a new coroutine that yields three times and finally prints "Done" + +```js +my_coro = coroutine(=> { + yield(1) + yield(2) + yield(3) + print("Done") +}) +``` + +Now we can resume the coroutine up to 4 times, and each time it will resume from the last `yield` and stop at the next one, or when it reaches the end of the function. + +``` +first_yield = resume(coro) +// At this point the coroutine is paused on its first line +print(first_yield) // prints 1 + +second_yield = resume(coro) +// At this point the coroutine is paused on its second line +print(second_yield) // prints 2 + +third_yield = resume(coro) +// At this point the coroutine is paused on its third line +print(third_yield) // prints 3 + +resume(coro) // prints "Done" +// At this point the coroutine has completed its execution. +``` + The big difference is: A coroutine can **yield** more than once, and will be paused in between. And that is really all there is to them, from a technical level. A simple example of this would look like this. ## Classifying Coroutines