Lua Advanced: Coroutines, Metamethods & Performance

Lesson 1 of 5

Coroutines: Cooperative Multitasking

A coroutine is an independent thread of execution that you can pause and resume by hand, unlike OS threads, only one coroutine (or the main program) ever runs at a time, so there's no race condition to worry about.

Creating and resuming a coroutine

Lua
  • coroutine.create(fn) builds a coroutine without running it yet.
  • coroutine.resume(co, ...) starts/continues it, passing ... in as arguments (either to the function itself, the first time, or as coroutine.yield's return value on later resumes).
  • coroutine.yield(...) pauses the coroutine and hands ... back to whoever called resume.
  • coroutine.status(co) reports "suspended", "running", "normal", or "dead".

A generator built on coroutines

Lua

coroutine.wrap is coroutine.create plus automatic resume calls, wrapped in a plain function you can call directly (or use in a for ... in loop), it's the idiomatic way to build a lazy generator/iterator in Lua.

WARNING

Unlike pcall, an error raised inside a coroutine created with coroutine.wrap propagates as a normal Lua error to the caller of the wrapped function. A coroutine made with plain coroutine.create, by contrast, reports the error as its second resume return value instead of raising it, check coroutine.resume's boolean result if you use create directly.

📝 Coroutines Quiz

Passing score: 70%
  1. 1.What does coroutine.yield do?

  2. 2.Two Lua coroutines can execute simultaneously on separate CPU cores.

  3. 3.____.wrap(fn) returns a plain callable function that automatically resumes the coroutine each call, ideal for building generators.