Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 32 ยท Errors, Modules and Coroutines

Coroutines

Learn Lua coroutines: create, resume, yield, status and wrap, passing values both ways, writing generators and producers, and a simple cooperative scheduler.

A normal function runs from start to finish, and the caller waits. A coroutine is a function that can pause in the middle, hand a value back to whoever started it, and later continue exactly where it stopped, with all its local variables intact. It is one of Lua's most distinctive features, and it lets you write generators, pipelines and cooperative multitasking without threads or callbacks.

In this lesson you will learn the four functions that do most of the work (create, resume, yield and status), how values travel in both directions, the wrap shortcut that turns a coroutine into an iterator, and how to build a small round-robin scheduler. You should be comfortable with functions and closures.

Lua is not installed on this site, so the Lua listings are read-only and show real output. The runnable examples are JavaScript stand-ins built on generator functions, which pause and resume in a very similar way.

The life of a coroutine

suspended Created, or paused at a yield.
running Currently executing.
normal Active, but resumed another coroutine.
dead Finished or failed with an error.
1 / 2

Creating and resuming

coroutine.create(f) takes a function and returns a thread object (the Lua type is called thread). Nothing runs yet; the coroutine starts out suspended. coroutine.resume(co, ...) starts or continues it. Inside the body, coroutine.yield(...) pauses it and gives control back to the resumer.

LUA
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)
coroutine.resume(co)
print(coroutine.status(co))
coroutine.resume(co)
print(coroutine.status(co))
TEXT
suspended
step 1
step 2
suspended
step 3
dead

After the function returns, the coroutine is dead and cannot be resumed again. Trying it gives false, "cannot resume dead coroutine" rather than raising an error, because resume itself works like pcall.

Passing values both ways

The real power comes from the values that cross the boundary. The arguments of the first resume become the parameters of the function. Later, the arguments of each resume become the return values of the yield that was waiting. In the other direction, the arguments of yield become the extra results of resume after the leading true, and the final return values do the same.

LUA
local co = coroutine.create(function(a, b)
  print("start", a, b)
  local c = coroutine.yield(a + b)
  print("got", c)
  local d, e = coroutine.yield(c * 2)
  print("got", d, e)
  return "done"
end)

print(coroutine.resume(co, 1, 2))
print(coroutine.resume(co, 10))
print(coroutine.resume(co, "x", "y"))
print(coroutine.status(co))
print(coroutine.resume(co))
TEXT
start	1	2
true	3
got	10
true	20
got	x	y
true	done
dead
false	cannot resume dead coroutine

Read it line by line. The first resume passes 1, 2 as a, b, runs to the first yield, and resume returns true, 3. The second resume passes 10, which becomes c; the coroutine prints, then yields 20. The third passes two values, and the function finishes by returning "done".

Errors inside coroutines

If the body raises an error, the coroutine dies and resume returns false plus the error value; the program does not stop. That makes resume convenient, but remember to check its first result. The error handling ideas from Error Handling apply: you can throw table error objects, and coroutine.close(co) (Lua 5.4) kills a suspended coroutine and runs its pending <close> variables.

JS Generators model a coroutine's pause and resume

Press Run (or Ctrl + Enter) to see the console output here.

No output.

wrap: a coroutine as a function

coroutine.wrap(f) returns an ordinary function. Each call resumes the coroutine, and the call's results are the values that were yielded or returned. There is no leading true, and errors are not caught: they propagate to the caller. Calling a dead wrapped coroutine raises an error.

That makes wrap the natural way to write iterators for the generic for loop (see Iterating with pairs and ipairs):

LUA
local function countdown(n)
  return coroutine.wrap(function()
    for i = n, 1, -1 do
      coroutine.yield(i)
    end
  end)
end

for value in countdown(3) do
  print(value)
end
TEXT
3
2
1

When the function returns without yielding, the wrapper returns nil, and for ends. Compare this with writing the same iterator using closures: the coroutine version keeps its loop state in ordinary local variables, which is far easier for anything recursive. A classic example is walking a tree:

LUA
local function walk(node)
  if node then
    walk(node.left)
    coroutine.yield(node.value)
    walk(node.right)
  end
end

local function inorder(root)
  return coroutine.wrap(function() walk(root) end)
end

A yield may happen several function calls deep, as it does inside the recursive walk; it pauses the whole coroutine, not just the innermost function.

Producers and consumers

Coroutines suit pipelines where one stage produces values and another consumes them, without building the whole list in memory:

LUA
local function producer()
  return coroutine.wrap(function()
    for _, line in ipairs({"alpha", "beta", "gamma"}) do
      coroutine.yield(line)
    end
  end)
end

local function filter(source, pattern)
  return coroutine.wrap(function()
    for line in source do
      if line:find(pattern) then
        coroutine.yield(line:upper())
      end
    end
  end)
end

for line in filter(producer(), "a") do
  print(line)
end
TEXT
ALPHA
BETA
GAMMA

Every word contains an a, so all three pass. Each stage pulls values from the previous one only when it needs them, which is called lazy evaluation.

JS A lazy pipeline with generators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Cooperative scheduling

Lua coroutines are cooperative: a coroutine runs until it yields on its own. Nothing interrupts it, so there are no data races between coroutines, but a coroutine that never yields blocks the whole program. A scheduler is just a loop that resumes each task in turn and removes the ones that finish.

LUA
local tasks = {}

local function spawn(name, steps)
  tasks[#tasks + 1] = {name = name, co = coroutine.create(function()
    for i = 1, steps do
      print(name, "step", i)
      coroutine.yield()
    end
  end)}
end

spawn("A", 2)
spawn("B", 3)

while #tasks > 0 do
  for i = #tasks, 1, -1 do
    local task = tasks[i]
    coroutine.resume(task.co)
    if coroutine.status(task.co) == "dead" then
      table.remove(tasks, i)
    end
  end
end

The loop walks the list backwards so table.remove does not skip anything, which means task B runs before task A in every round. The output interleaves the two tasks:

TEXT
B	step	1
A	step	1
B	step	2
A	step	2
B	step	3

Game engines use this idea for scripted events ("walk to the door, wait two seconds, open it"), where each task yields until its next frame or timer.

JS A round-robin scheduler

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other useful functions

  • coroutine.running() returns the running coroutine and a boolean that is true for the main thread.
  • coroutine.isyieldable() tells you whether yield is allowed right now.
  • coroutine.close(co) closes a suspended or dead coroutine (Lua 5.4).
  • You can yield across a pcall, so protected calls inside coroutines work as you would hope.
  • A coroutine cannot yield from inside a C function that does not support it, such as a table.sort comparator.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does coroutine.resume(co, 1, 2) do the very first time it is called on a fresh coroutine?

    The first resume starts the function, and its extra arguments become the function's parameters. Later resumes feed the waiting yield.
  2. 2. A coroutine's function has returned. What does coroutine.status report?

    A coroutine is dead once its function returns or fails with an error. The four statuses are suspended, running, normal and dead.
  3. 3. How does coroutine.wrap differ from coroutine.create plus resume?

    The wrapped function returns the yielded values directly and raises errors instead of returning false.
  4. 4. What happens if a coroutine never calls yield and loops forever?

    Nothing interrupts a coroutine. Control only returns when it yields or finishes.
  5. 5. In which direction do the arguments of coroutine.yield(x) travel?

    yield values come back from resume after the leading true, while the arguments of resume become the results of yield.

Summary

  • A coroutine is a function that can pause with coroutine.yield and continue with coroutine.resume.
  • Its status is suspended, running, normal or dead.
  • Values flow both ways: resume arguments go in, yield arguments come out.
  • coroutine.wrap gives you a generator function that works directly in a for loop.
  • Coroutines are cooperative, so a scheduler loop decides who runs next.
  • Errors inside a coroutine kill only that coroutine; resume reports them as false, err.

Next, see how Lua talks to files and the operating system in Files and I/O.