coroutine
Cooperative threads of Lua 5.1 / LuaJIT 2.1. A coroutine has its own stack and runs until it yields or finishes.
coroutine.isyieldable does not exist in LuaJIT 2.1 and is not available in this VM.
Functions
coroutine.create(f: function): thread
coroutine.create(f: function): thread
- Creates a new coroutine that will run
f, and returns it. The coroutine starts suspended.
coroutine.resume(co: thread, ...: any): boolean, any
coroutine.resume(co: thread, ...: any): boolean, any
- Starts or continues the coroutine
co. Extra arguments are passed to the body function on the first resume, or become the results ofcoroutine.yieldon later resumes. - On success returns
trueplus the values passed toyield, or the values returned by the body when it finishes. - On error returns
falseplus the error value; the coroutine is then dead. - Resuming a dead coroutine returns
false, "cannot resume dead coroutine".
local co = coroutine.create(function(a, b)
local c = coroutine.yield(a + b)
return c * 2
end)
print(coroutine.resume(co, 1, 2))
print(coroutine.resume(co, 10))
coroutine.running(): thread | nil
coroutine.running(): thread | nil
- Returns the running coroutine, or
nilwhen called from the main thread (Lua 5.1 semantics).
coroutine.status(co: thread): string
coroutine.status(co: thread): string
- Returns
"running"ifcois the running coroutine,"suspended"if it has yielded or not started,"normal"if it is active but has resumed another coroutine, and"dead"if it finished or failed.
coroutine.wrap(f: function): function
coroutine.wrap(f: function): function
- Creates a coroutine like
createand returns a function that resumes it each time it is called. - Arguments of the call are passed to
resume; returned values are the values yielded or returned. - Errors are propagated to the caller instead of being returned.
local gen = coroutine.wrap(function()
for i = 1, 3 do coroutine.yield(i) end
end)
print(gen(), gen(), gen())
coroutine.yield(...: any): any
coroutine.yield(...: any): any
- Suspends the running coroutine. The arguments become extra results of the
resumethat started this run. - Returns the arguments passed to the next
resume. - Errors if called outside a coroutine.