Pico-8 Wiki


162pages on
this wiki
Add New Page
Comments0 Share
cocreate( func )

Creates a coroutine from a function.

The coroutine function.

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 value 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 object.

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 Edit

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

cor = nil

function anim()
  for i=4,124,4 do

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

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

See also Edit

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.