Coroutines

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.

Syntax

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

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
    end
  end
)

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.

Coroutines

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

All contributors

Looking to contribute?

Learn Lua on Codecademy