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:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Thinking coroutines run in parallel
- Expecting a coroutine to run as soon as it is created
- 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: