Coroutines

Coroutines are special functions that can pause execution to allow other code to run, and resume execution form where it left off.

Vortex functions become coroutines when the yield statement is found within their body.

Calling a coroutine function returns a function that is ready for execution.

const coro = () => {
    var x = 0
    while (true) {
        yield x
        x += 1
    }
}

const c = coro() // This sets up and returns a ready coroutine

c().println() // 0
c().println() // 1
c().println() // 2

Coroutines expose a hidden variable called _value. This variable starts off as the value None, however if we pass an argument into the coroutine function, it gets assigned to value.

const coro = () => {
    var x = 5
    while (true) {
        yield x + _value
    }
}

const c = coro() // This sets up and returns a ready coroutine

c(5).println() // 10
c(3).println() // 8
c().println() // This will not error, because the previous call has already set the _value to 3. If the first coroutine call did not provide a valid argument, an error will then be raised

If a coroutine finishes execution, ie. there are no more yield statements, it is considered to be done and any further calls will simply return None.

You can manually end a coroutine by including a return statement in the function's body.

Checking Coroutine State

Calling the builtin function info on the coroutine will show you its state:

c.info().println()

// { name: coro_0, arity: 0, params: [], generator: true, init: true, done: false }

The info call provides information about the function, including whether or not it is a generator (coroutine), if it has been initialised or not, and if it has finished its execution.

Last updated