TExcelTAD
Home › Lua › Lua Coroutines

Lua Coroutines

A coroutine is a function that can pause itself in the middle (coroutine.yield) and later continue where it left off (coroutine.resume). Unlike operating-system threads, coroutines never run at the same time: exactly one runs, and it decides when to hand control back. That makes them simple and free of race conditions.

lua · try it yourself
local co = coroutine.create(function()
  print("step 1")
  coroutine.yield()
  print("step 2")
  coroutine.yield()
  print("step 3")
end)

print(coroutine.status(co))
coroutine.resume(co)
print("-- back in main")
coroutine.resume(co)
coroutine.resume(co)
print(coroutine.status(co))
suspended
step 1
-- back in main
step 2
step 3
dead

The coroutine API

Function Purpose
coroutine.create(f) make a new coroutine (type thread) from a function
coroutine.resume(co, …) start or continue it; returns true + yielded values, or false + error
coroutine.yield(…) pause the running coroutine, sending values back to resume
coroutine.status(co) "suspended", "running", "normal" or "dead"
coroutine.wrap(f) like create, but returns a function that resumes it (errors propagate)
coroutine.isyieldable() can the current code yield?
coroutine.running() the running coroutine
coroutine.close(co) close a suspended coroutine (runs pending <close> variables)

Passing values both ways

Values flow in both directions: arguments of resume become the results of yield inside the coroutine, and arguments of yield become the results of resume outside:

lua · try it yourself
local co = coroutine.create(function(a, b)
  print("started with", a, b)
  local c = coroutine.yield(a + b)
  print("received", c)
  local d, e = coroutine.yield(c * 2)
  print("received", d, e)
  return "finished"
end)

print(coroutine.resume(co, 1, 2))
print(coroutine.resume(co, 10))
print(coroutine.resume(co, "x", "y"))
print(coroutine.resume(co))
started with	1	2
true	3
received	10
true	20
received	x	y
true	finished
false	cannot resume dead coroutine

Generators with wrap

coroutine.wrap returns a plain function, which makes coroutines great generators for the generic for. The producer code reads like a normal loop, with yield wherever it has a value:

lua · try it yourself
local function fibonacci(limit)
  return coroutine.wrap(function()
    local a, b = 0, 1
    while a <= limit do
      coroutine.yield(a)
      a, b = b, a + b
    end
  end)
end

for n in fibonacci(100) do io.write(n, " ") end
print()

local function permutations(list, n)
  n = n or #list
  return coroutine.wrap(function()
    if n <= 1 then
      coroutine.yield(list)
    else
      for i = 1, n do
        list[n], list[i] = list[i], list[n]
        for p in permutations(list, n - 1) do coroutine.yield(p) end
        list[n], list[i] = list[i], list[n]
      end
    end
  end)
end

for p in permutations({ "a", "b", "c" }) do io.write(table.concat(p), " ") end
print()
0 1 1 2 3 5 8 13 21 34 55 89 
bca cba cab acb bac abc 

Writing a permutation iterator without coroutines would need an explicit stack; with them, the recursive algorithm just yields each result.

Producer and consumer

Coroutines shine when one piece of code produces data and another consumes it, each written as its own simple loop:

lua · try it yourself
local function producer(lines)
  return coroutine.create(function()
    for _, line in ipairs(lines) do coroutine.yield(line) end
  end)
end

local function upperFilter(source)
  return coroutine.create(function()
    while true do
      local ok, line = coroutine.resume(source)
      if not line then return end
      coroutine.yield(line:upper())
    end
  end)
end

local pipeline = upperFilter(producer({ "alpha", "beta", "gamma" }))
while true do
  local _, line = coroutine.resume(pipeline)
  if not line then break end
  print(line)
end
ALPHA
BETA
GAMMA

Scripted sequences in games

Game engines resume coroutines once per frame, so a character's behaviour can be written as a story rather than a state machine:

lua · try it yourself
local function patrol(name)
  return coroutine.create(function()
    for _, spot in ipairs({ "gate", "tower", "well" }) do
      print(name .. " walks to the " .. spot)
      coroutine.yield()            -- wait for the next frame
    end
    print(name .. " rests")
  end)
end

local guards = { patrol("Ash"), patrol("Bea") }
for frame = 1, 4 do
  print("frame " .. frame)
  for _, g in ipairs(guards) do
    if coroutine.status(g) ~= "dead" then coroutine.resume(g) end
  end
end
frame 1
Ash walks to the gate
Bea walks to the gate
frame 2
Ash walks to the tower
Bea walks to the tower
frame 3
Ash walks to the well
Bea walks to the well
frame 4
Ash rests
Bea rests

Errors inside coroutines

An error in a coroutine doesn't crash the caller: resume returns false and the message, and the coroutine is dead. With wrap, the error is re-raised in the caller instead:

lua · try it yourself
local co = coroutine.create(function() error("boom", 0) end)
print(coroutine.resume(co))
print(coroutine.status(co))

local gen = coroutine.wrap(function() error("wrapped boom", 0) end)
print(pcall(gen))
false	boom
dead
false	wrapped boom

Test yourself

Can two Lua coroutines run at the same moment on different CPU cores?

  1. Yes
  2. No, only one runs at a time and it yields control explicitly
  3. Only with coroutine.wrap
  4. Only in LuaJIT

What does coroutine.resume(co, 5) do with the 5 when co is suspended at a yield?

  1. It is ignored
  2. It becomes the return value of that yield call
  3. It is added to the coroutine's arguments table
  4. It sets the coroutine's status

What is the status of a coroutine whose function has returned?

  1. suspended
  2. finished
  3. dead
  4. normal