This article is generally only relevant to advanced users. Don't worry if you don't quite understand anything here.
A coroutine (referred to in code as a thread) is a representation of a function paused in the middle of execution. Coroutines contain everything needed to pause and subsequently resume execution of a function, including the statement being executed, the complete call stack, and the values of local variables.
Unlike threads in other languages, coroutines are never scheduled implicitly—they must be handled explicitly, for instance, by using the Parallel API.
Unlike all other Lua types, there are no coroutine literals: they must be created and manipulated using functions of the Coroutine API. A coroutine can be created from a function by using coroutine.create.
local c = coroutine.create(function() print("foo") coroutine.yield() print("bar") end)
After creation, a coroutine may be resumed several times, as long as
its status is not
dead (see coroutine.status).
Note that a coroutine does not start executing until it
is resumed for the first time!
print(coroutine.status(c)) -- suspended coroutine.resume(c) -- prints "foo"
After the function returns, it may not be resumed again, and there is no way to restart it.
coroutine.resume(c) -- prints "bar" print(coroutine.status(c)) -- dead assert(coroutine.resume(c)) -- errors with "cannot resume dead coroutine"
Communicating with Coroutines
The arguments given to coroutine.resume will be returned from
coroutine.yield, and vice-versa. Since the first
resume corresponds to starting the function, the first
set of values passed to coroutine.resume are used for the
local c = coroutine.create(function(x) print(x) local y = coroutine.yield(123) print(y) end) local ok, value = coroutine.resume(c, "foo") -- prints "foo" print(value) -- 123 coroutine.resume(c, "bar") -- prints "bar"
local c = coroutine.create(function(x) error("no coroutine for you!") end local ok, err = coroutine.resume(c) print(ok) -- false