Lesson 3 of 9 · 22m
Coroutines: Cooperative Control Flow Without Async Noise
Lua coroutines as resumable computation — how yield/resume really works, why they fit scripting, and where they fail under host reentrancy.
Lua coroutines are not threads and they are not a miniature async runtime. They are independent stacks that can pause and later continue. That makes them perfect for scripted sequences: dialogue, AI state machines, iterators, cutscenes, and game logic that wants to say 'wait three ticks' without splitting code across callbacks.
The core operations
local routine = coroutine.create(function()
print("start")
coroutine.yield("paused once")
print("resumed")
return "done"
end)
print(coroutine.resume(routine)) -- true, paused once
print(coroutine.status(routine)) -- suspended
print(coroutine.resume(routine)) -- true, done
print(coroutine.status(routine)) -- deadresume returns success followed by yielded or returned values. A yielded coroutine keeps its local variables and instruction position. Nothing runs concurrently; exactly one coroutine is active at a time because control is explicitly transferred.
A practical game pattern
local function patrol(enemy)
while true do
enemy:move_to("gate")
coroutine.yield("sleep", 2.0)
enemy:move_to("bridge")
coroutine.yield("sleep", 2.0)
end
endThe host scheduler owns time. Each tick it resumes active routines, interprets yielded instructions, and puts them back into a timer queue. The script reads linearly even though the engine remains single-threaded and deterministic.
Coroutine.wrap is convenient but hides errors
local next_event = coroutine.wrap(function()
yield_event("spawn")
yield_event("boss")
end)wrap returns a function that raises errors instead of returning false, err. For infrastructure code, explicit resume is usually better because failure is data you can log, attribute, and sandbox.
Where coroutines bite
You cannot yield across certain host boundaries. In classic Lua, a coroutine cannot yield through a C function that did not arrange for it; LuaJIT and Lua 5.2+ relax parts of this, but host callbacks can still create non-yieldable frames. The symptom is often attempt to yield across C-call boundary or a script that mysteriously completes in the wrong order.
The other trap is cooperative means cooperative. A loop without yield blocks the entire host thread. Coroutines do not protect you from CPU-bound scripts.
Field notes
- Always check the boolean from
coroutine.resume; silent script death is worse than a visible exception. - Give yielded values a protocol:
{"sleep", seconds}or tagged strings, not arbitrary host objects. - Coroutine state is serialization-hostile. If save files must capture scripts, persist logical state rather than raw coroutine stacks.
- Do not use coroutines to imitate parallelism. Lua states are normally single-threaded, and shared host data still needs ownership rules.
Was this lesson helpful?