Cocreate

From Pico-8 Wiki
Jump to navigation Jump to search
cocreate( func )
Creates a coroutine from a function.
func
The function for the coroutine to run.

return-value
A new coroutine.

A coroutine is a special kind of function that can yield control back to the caller without completely exiting. The caller can then resume the coroutine as many times as needed until the function exits.

To create a coroutine, call cocreate() with a function. This function is expected to take no arguments, to return no value, and to call yield() to temporarily return control to the caller. cocreate() returns the coroutine that can be used to control execution of the function.

cocreate() does not call the coroutine function. Instead, the caller is expected to call coresume() with the coroutine to start or resume execution of the function.

The coroutine function calls yield() to suspend execution and return control to the caller of coresume(). The function can also call another function that calls yield(), and the entire call stack will be preserved. The coroutine function continues from where it left off the next time you call coresume() with the coroutine.

If the coroutine function returns instead of yields (such as by allowing control to reach the end of the function body, or by using return), the coroutine dies and cannot be revived by coresume(). You can test the status of a coroutine object by calling the costatus() function.

Coroutines are useful for preserving the state of a function in progress for later continuation. It is a way to preserve state, and is well suited to pausing and resuming a sequence of actions that terminates. This works especially well with the PICO-8 game loop as a way to initiate an action that takes place over multiple frames.

Caution: As of PICO-8 v0.1.10, if a runtime error occurs inside a coroutine function, the function aborts, but instead of stopping the program and printing an error message, the coroutine dies and execution continues. This can make debugging coroutines difficult, as many common errors (such as incorrect nil values) manifest as runtime errors.

Examples

The following example uses a coroutine to animate a circle moving across the screen. The animation is initiated by pressing button 5.

x=4
y=4
cor = nil

function anim()
  for i=4,124,4 do
    x=i
    y=i
    yield()
  end
end

function _update()
  if btnp(5) then
    cor = cocreate(anim)
  end
  if cor and costatus(cor) != 'dead' then
    coresume(cor)
  else
    cor = nil
  end
end

function _draw()
  cls()
  circfill(x, y, 4, 7)
end

See also