Skip to content
1 / 5
Lesson 01 of 05

Coroutine Basics

Create and manage cooperative threads with coroutines in Luau.

Coroutines enable cooperative multitasking within a single script. Unlike parallel execution, only one coroutine runs at a time — they yield control voluntarily.

Creating coroutines:

  • coroutine.create(func) — returns thread object
  • coroutine.wrap(func) — returns a function that resumes the coroutine

Controlling coroutines:

  • coroutine.resume(thread, ...) — start or continue execution
  • coroutine.yield(...) — pause and return values to resumer
  • coroutine.status(thread) — check state

Thread states:

  • "suspended" — created or yielded (not running)
  • "running" — currently executing
  • "dead" — finished or errored
  • "normal" — resumed another coroutine

Passing data:

  • Arguments to resume() become the return values of yield() inside
  • Arguments to yield() become the return values of resume() outside

Error handling: coroutine.resume returns: true, values on success OR false, errorMessage on error Errors don't crash the main thread — they stop the coroutine.

luau
1-- Basic coroutine
2local function countdown(from)
3 for i = from, 1, -1 do
4 print("Countdown:", i)
5 coroutine.yield() -- pause each iteration
6 end
7 print("Blast off!")
8end
9
10local co = coroutine.create(countdown)
11
12-- Resume step by step
13coroutine.resume(co, 5) -- starts, runs to first yield
14coroutine.resume(co) -- continues to next yield
15coroutine.resume(co) -- continues...
16
17print(coroutine.status(co)) -- "suspended" (still yielded)
18
19-- Passing data back and forth
20local function conversation()
21 local question = coroutine.yield("What is 2+2?") -- yield = ask
22 print("Answer received:", question)
23 coroutine.yield("Correct! What is 5*5?")
24 local answer2 = coroutine.yield()
25 print("Second answer:", answer2)
26end
27
28local conv = coroutine.create(conversation)
29local ok, q1 = coroutine.resume(conv) -- start
30print(q1) -- "What is 2+2?"
31local ok2, q2 = coroutine.resume(conv, 4) -- answer=4
32print(q2) -- "Correct! What is 5*5?"
33coroutine.resume(conv, 25)
34
35print(coroutine.status(conv)) -- "dead" (finished)
READY · 35 lines