Concepts - Coroutines
Coroutines Vs Threads
Lua is not multi-threaded.
However, we emulate a multi-threaded behavior using coroutines. A coroutine is like a thread, as in it has its own execution flow. coroutines work in a cooperative nature, meaning while only one can execute at a time we are able to pause these "threads" during execution to allow other to run.
threads are what is returned by the creation of a coroutine in lua. These have no properties or member functions, but the thread objects are passed to coroutine.resume to tell which coroutine to start executing again.
Basics
Lua provides coroutine functionality through the coroutine table. You can create a coroutine using coroutine.create, which takes a function as its argument. It returns a value of type thread, representing the new coroutine:
When a coroutine is created, it starts in the suspended state:
To start (or resume) a coroutine, use coroutine.resume. This changes its state from suspended to running:
After it finishes running, its state becomes dead:
Yielding
Coroutines become useful with coroutine.yield, which pauses their execution and allows them to be resumed later.
Now, resuming the coroutine steps through it one iteration at a time:
Trying to resume a dead coroutine results in an error:
Passing Values Between resume and yield
Coroutines can exchange data with the code resuming them:
Pass arguments into the coroutine:
Get return values from yield:
Send values into a suspended coroutine:
Return values from the coroutine function: