CodeRigor

FREE LESSON

Coroutines, yield & resume protocols

Separate yielded values, completion and errors using resume results and coroutine status.

Before this lesson, complete lua-iterators.

This course runs standard Lua 5.5 with its standard library. Game engines, LuaJIT and embedded host APIs are outside this sequence.

A coroutine is a cooperatively resumed computation. Creating one does not run its body; it starts suspended. Resume runs until the body yields, returns or raises an error. Yield suspends execution while retaining local state, so a later resume continues after the yield point. This does not create an operating-system thread or promise parallel execution.

A coroutine lifecycle
start / 3
A coroutine lifecycle

Apply the contract

Coroutine.resume returns a success Boolean followed by yielded values or final return values. On an error it returns false and an error value. The Boolean tells you whether the resume operation succeeded, not whether the coroutine is finished. Inspect coroutine.status when completion matters. A successful yield of nil is distinct from a failed resume, and the coroutine can remain suspended after yielding that nil.

Resume has two channels
start / 3
Resume has two channels
Lua
local co=coroutine.create(function()
  coroutine.yield(false)
  return "done"
end)
print(coroutine.resume(co))
print(coroutine.status(co))
print(coroutine.resume(co))
print(coroutine.status(co))

Reason about the edge cases

The producer in this lab visits a caller-supplied extent and yields each indexed value, including nil, false and zero. After the last yield it still needs another resume to reach its final return of done. At that point status becomes dead; another resume fails. Do not use a value's truthiness as a proxy for completion, or false and nil records disappear. Tests observe both the returned values and the state after every resume. This separates data from control state and makes the contract deterministic without relying on wall-clock scheduling.

Nil can be yielded data
start / 3
Nil can be yielded data

Practice

Implement M.make(values,n) returning a new coroutine thread. Each of its first n successful resumes yields the corresponding table entry, even nil, false or zero. The following resume returns the final value done and the thread becomes dead. Use explicit n rather than the input table length. Calls after completion follow Lua’s normal dead-coroutine resume behavior.

Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The first part introduces Lua through its language designer. The authored lesson and Lua 5.5 manual cover the exact APIs and advanced details in this lab.