Coroutines
Coroutines allow collaborative multitasking and are a very interesting aspect of Lua. Keep in mind that coroutines are not threads. Using coroutines will help you save time when you need different workers using the same context, and it also produces code that is easier to read and therefore maintain.
Creating a coroutine
To create a coroutine, use the coroutine.create function. This function only creates the coroutine but is not actually executed:
local nt = coroutine.create(function() print("w00t!")
end)
Executing a coroutine
To execute a coroutine, use the coroutine.resume function:
coroutine.resume(<coroutine>)
You can also pass parameters to the coroutine function as additional arguments to the coroutine.resume function:
local nt = coroutine.create(function(x, y, z) print(x,y,z) end) coroutine.resume(nt, 1, 2, 3)
The output will be as follows:
1,2,3
Important note
There is a function named coroutine.wrap that can replace...