Coroutines

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.

Creating a coroutine

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)

Executing a coroutine

To execute a coroutine, use the coroutine.resume function:

coroutine.resume(<coroutine>)

You can also pass parameters to the coroutine function ...

Get Mastering the Nmap Scripting Engine now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.