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.
To create a coroutine, use the function coroutine.create
. This function only creates the coroutine but is not actually executed:
local nt = coroutine.create(function() print("w00t!") end)
To execute a coroutine, use the function coroutine.resume
:
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