Coroutines
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
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours