Lua Thread and Coroutines

Lua Thread and Coroutines#

The Lua environment is single threaded and is run on dedicated thread. This means that a long running or blocking call in an event handler or other Lua code can negatively impact all Lua code, including other event handlers

However, this does not mean there are no options for concurrency or that long running tasks must negatively impact all other Lua code. Instead, Lua offers coroutines.

Coroutines allow a long running task to yield, or suspend execution to allow either other Lua functions to continue.

Note

The initial run of autload.lua is run as a coroutine, however module authors should refrain from running long running or blocking tasks when their module is loaded.

Instead, long running or blocking tasks at startup should be performed in a startup event handler.

Simple Coroutine Setup#

An event handler that is performing a long running task, especially one with tight loops, can simply coroutine.yield() occasionally. This will stop execution at each yield and allow other events to continue. After all other events have either completed or yielded, the event will resume after the yield until it yields again or completes normally.

Advanced Usage: Lua-side coroutines#

Coroutines can also be setup directly within Lua itself. This can be used to monitor some other Lua function that uses coroutines or similar situations.

Note

The function must still coroutine.yield itself or it will block the Lua/render thread. In most cases the function should probably yield every time the inner coroutine does.