← Back to Lua Course | Chapter 7: Coroutines | Lesson 1 of 7

What are coroutines

A coroutine is a function that can pause in the middle and be resumed later where it left off.

In this page:

  1. What are coroutines

What are coroutines

A coroutine is an independent thread of execution with its own stack, but only one runs at a time. It runs until it yields or finishes, and control passes back explicitly, which is called cooperative multitasking. Coroutines are not operating-system threads and never run in parallel.

Note: Coroutines have the type "thread" in Lua, and creating thousands of them is cheap.

Example: What are coroutines

lua
local co = coroutine.create(function()
  print("inside the coroutine")
end)
print(type(co))
print("before resume")
coroutine.resume(co)
print("after resume")

-- Output:
-- thread
-- before resume
-- inside the coroutine
-- after resume
Common Mistakes
  1. Thinking coroutines run in parallel
  2. Expecting a coroutine to run as soon as it is created
  3. Confusing them with operating-system threads
Chapter Summary
  • Coroutines pause and resume
  • Only one runs at a time
  • They switch cooperatively
  • Their type is thread
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.