Skip to main content

Module coroutine

Module coroutine 

Source
Expand description

The coroutine library.

Coroutines are collaborative multithreading: each coroutine is an independent thread of execution that suspends itself explicitly with coroutine.yield and is resumed from the outside with resume.

local co = coroutine.create(function(a)
  local b = coroutine.yield(a + 1)
  return b * 2
end)
print(coroutine.resume(co, 1))   --> true   2
print(coroutine.resume(co, 10))  --> true   20

Functionsยง

close
Closes the coroutine, i.e. closes all its pending to-be-closed variables and puts it in a dead state. The coroutine must be dead or suspended. Returns true on success, or false plus an error object.
create
Creates a new coroutine with body f, which must be a function. Returns the new coroutine, an object with type "thread".
isyieldable
Returns true when the running coroutine can yield โ€” that is, when it is not the main coroutine and it is not inside a non-yieldable C function.
resume
Starts or continues the execution of the coroutine co. On the first resume, the values are passed as arguments to the body function; on later resumes, they become the results of the pending coroutine.yield.
running
Returns the running coroutine plus a boolean that is true when the running coroutine is the main one.
status
Returns the status of the coroutine co, as a string: "running", "suspended", "normal" (active but not running), or "dead".
wrap
Creates a new coroutine with body f and returns a function that resumes it each time it is called. Arguments to that function pass into the coroutine, and its yielded values come back as results โ€” but unlike resume, errors are propagated to the caller.
yield
Suspends the execution of the calling coroutine. Any arguments are returned as extra results by the resume that woke the coroutine up; symmetrically, yield returns the extra values passed to the next resume.