Functions

Lua Coroutines

Using Coroutines

Lua coroutines enable cooperative multitasking with yield.

What are Lua Coroutines?

Lua coroutines provide a powerful mechanism for implementing cooperative multitasking. Unlike threads that are preemptive, coroutines are collaborative, meaning they yield control back to each other voluntarily. This makes them lightweight and efficient for certain tasks.

Basic Coroutine Operations

Lua provides several functions to work with coroutines. The key functions include:

  • coroutine.create: Creates a new coroutine.
  • coroutine.resume: Resumes a coroutine.
  • coroutine.yield: Yields the running coroutine.
  • coroutine.status: Returns the status of the coroutine.
  • coroutine.wrap: Creates a coroutine and wraps it in a function.

Creating and Resuming Coroutines

To create a coroutine, use the coroutine.create function, which takes a Lua function as its argument. The function defines the code that will run in the coroutine. You can start or resume execution of this coroutine using coroutine.resume. When a coroutine yields, it's paused at the yield point and can be resumed later.

Using Yield to Control Execution

The coroutine.yield function is used within a coroutine to pause its execution, effectively returning control to the point where the coroutine was resumed. This allows you to implement complex control flows and divide tasks into smaller, manageable chunks.

Coroutine Status

Coroutines have several statuses, which can be checked using coroutine.status:

  • suspended: The coroutine is not running but can be resumed.
  • running: The coroutine is currently executing.
  • dead: The coroutine has finished execution or encountered an error.

Understanding these statuses helps in managing coroutine lifecycles effectively.

Coroutine Wrapping with Wrap

The coroutine.wrap function simplifies coroutine usage by returning a function that, when called, resumes the coroutine. This can be more intuitive for certain use cases.

Previous
Varargs