Add example to coroutines post

This commit is contained in:
Talia 2023-07-20 21:21:52 +02:00
parent 46eccf2c4d
commit d08bb6dd10
Signed by: darkwiiplayer
GPG key ID: 7808674088232B3E

View file

@ -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