Coroutines are a very interesting feature of Lua that allow collaborative multitasking. Keep in mind that coroutines are not regular preemptive threads. Coroutines will help you save time when you need different workers that use the same context; they consume very few resources.
Let's learn the basics of coroutines. Later in Chapter 9, Parallelism, we will go into this subject in depth.
To create a coroutine, use the coroutine.create
function. This function creates the coroutine without executing it:
local nt = coroutine.create(function()print("w00t!") end)
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)
Here is the output of the preceding code:
1,2,3