A Coroutine is a collaborative thread of execution. Unlike operating system threads which are preemptive (the OS kernel forcibly switches context at arbitrary times), Lua coroutines are collaborative: a running coroutine retains CPU execution until it explicitly calls coroutine.yield().
Coroutine States and Lifecycle
A coroutine in Lua exists in one of four states:
suspended: Newly created or waiting to be resumed after yielding.running: Currently executing on the CPU.normal: Active, but has resumed another coroutine and is waiting for it.dead: Has finished execution or encountered an unhandled error.
-- Step 1: Create a coroutine
local co = coroutine.create(function(heroName)
print("1. Quest accepted by: " .. heroName)
-- Pause execution and pass data back to the caller!
local dungeonChoice = coroutine.yield("Approaching crossroad...")
print("2. Entering dungeon: " .. dungeonChoice)
return "Quest Completed!"
end)
print(coroutine.status(co)) -- suspended
-- Step 2: First resume starts the routine and passes initial arguments
local success, yieldValue = coroutine.resume(co, "Galahad")
print("Caller received: " .. yieldValue) -- "Approaching crossroad..."
print(coroutine.status(co)) -- suspended
-- Step 3: Second resume unblocks the yield, passing values INTO the coroutine!
local finalSuccess, finalResult = coroutine.resume(co, "Dragon's Lair")
print("Final Result: " .. finalResult) -- "Quest Completed!"
print(coroutine.status(co)) -- dead
Bidirectional Data Passing
Notice how data flows back and forth:
- Values passed to
coroutine.yield(a, b)emerge as the return values ofcoroutine.resume(). - Values passed to the subsequent
coroutine.resume(co, c, d)emerge as the return values of the waitingcoroutine.yield().
Generating Custom Iterators with coroutine.wrap
coroutine.wrap creates a coroutine and returns a plain Lua function that resumes the coroutine whenever called, raising errors directly to the caller:
local function rangeIterator(startVal, endVal, step)
step = step or 1
return coroutine.wrap(function()
local curr = startVal
while curr <= endVal do
coroutine.yield(curr)
curr = curr + step
end
end)
end
-- Use it directly in a generic for loop!
for val in rangeIterator(10, 50, 10) do
print("Generated value: " .. val) -- 10, 20, 30, 40, 50
end
Exercises
- Build a producer-consumer data pipeline where a producer coroutine yields stream data chunks consumed by a filter coroutine.
- Write a coroutine-based generator that yields prime numbers indefinitely.
- Compare the memory overhead of 50,000 Lua coroutines versus 50,000 OS operating system threads.