Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Sep 18, 2023
Contribute to Docs

Coroutines allow for the distribution and execution of multiple tasks as a set of concurrent processes. Coroutines do not provide parallelism: they can not be used to distribute work across multiple cores.


Coroutines can be created in two different ways, either by defining a function and passing it to coroutine.create(), or declaring the relevant logic as an anonymous function within the body of the coroutine.create() statement.

-- Option 1
local newFunc = function()
  -- Function body

local routineA = coroutine.create(newFunc)

-- Option 2
local routineB = coroutine.create(
  function() -- Anonymous function declaration
    -- Function body
    if -- Condition x
      coroutine.yield() -- The coroutine is paused until it is called again

Coroutine States

A coroutine can enter one of three states: suspended, running, or dead. This is what makes them useful, as they are essentially functions that can be paused and resumed at a later point. The status of a coroutine can be checked with the status() function and resumed using the resume() function. Once a coroutine has reached a dead state, it cannot be resumed again.

Functions in Coroutines

The following functions can be used to create, manage and terminate coroutines.


Allows the user to gracefully terminate a coroutine, freeing up associated resources in the process.
Returns a new coroutine with a function as an argument that will run within the new coroutine.
Resumes a coroutine.
Returns the running coroutine or nil if called in the main thread.
Returns a string indicating the status of the provided coroutine.
Returns a function that can resume a coroutine, acting like a thread but returning a function.
Suspends the coroutine and returns to the caller.

All contributors

Looking to contribute?

Learn Lua on Codecademy