CoreModules.Coroutine) provides functions for creating and managing Lua coroutines, which enable cooperative multitasking.
What are Coroutines?
Coroutines are independent execution threads that can be paused and resumed. Unlike preemptive threads, coroutines use cooperative multitasking - they explicitly yield control back to the caller. Key characteristics:- Lightweight (much cheaper than OS threads)
- Deterministic execution order
- No race conditions or locks needed
- Perfect for game logic, animations, and sequential workflows
Creating Coroutines
coroutine.create(func)
Creates a new coroutine.func- Function to run in the coroutine
coroutine.wrap(func)
Creates a coroutine and returns a function that resumes it.func- Function to run in the coroutine
coroutine.resume(), the wrapper function throws errors instead of returning them.
Running Coroutines
coroutine.resume(co [, …])
Resumes execution of a coroutine.co- Coroutine to resume...- Arguments to pass to the coroutine (or return fromyield)
trueplus return values if successfulfalseplus error message if error occurred
- First call: Starts the coroutine, arguments go to the function
- Subsequent calls: Resume from
yield, arguments becomeyield’s return values - After return: Cannot be resumed again
coroutine.yield(…)
Suspends execution and returns to the caller....- Values to return fromresume()
resume() call
Note: Can only be called from within a coroutine.
Coroutine Status
coroutine.status(co)
Returns the current state of a coroutine."suspended"- Created but not started, or yielded"running"- Currently executing"normal"- Active but not running (has resumed another coroutine)"dead"- Finished or encountered an error
coroutine.running()
Returns the currently running coroutine.- Current coroutine object
trueif running in the main thread,falseotherwise
Patterns and Examples
Generator Pattern
Producer-Consumer
Iterator with State
Async-style Operations
Pipeline Processing
State Machine
Tree Traversal
Error Handling
Best Practices
-
Use
wrapfor simple iterators -
Check coroutine status before resuming
-
Handle errors from resume
-
Use coroutines for sequential async operations
- Game animations
- Dialogue systems
- Tutorial sequences
- Level loading