Lua Coroutines

In this article, we will explore Lua coroutines, how they work, and how to use them effectively in your Lua programs.

Coroutines are a powerful feature of the Lua programming language that allows you to write asynchronous code in a synchronous style.

Using a coroutine in Lua, you can pause and resume a function.

A coroutine runs the function you specify, just like a regular function call. However, unlike regular functions, a coroutine can execute at any point, allowing another coroutine to take over.



What are Lua Coroutines?

Coroutines are a special type of Lua function that can yield control back to the caller while maintaining its own state.

This allows multiple coroutines to run concurrently within the same Lua thread.

When a coroutine yields, it suspends its execution and returns a value to the caller.

The caller can then resume the coroutine at a later time, passing in a new value to be used in the next iteration of the coroutine.


Lua Coroutine Functions

The coroutine library provides several functions that allow you to create, resume, and yield coroutines.

Coroutine FunctionsOverview
coroutine.create(f)Creates a new coroutine with the function f. When the coroutine is resumed for the first time, the function f will be executed.
coroutine.resume(co, …)Resumes the coroutine co passed as argument. If the coroutine was suspended before, it continues execution from where it left off. The optional arguments passed to resume are the values to be passed to the coroutine as arguments. If the coroutine was not suspended before, the resume starts at the beginning.
coroutine.yield(…)Suspends the coroutine and returns to the caller. The yield function returns the arguments passed to the resume call when the coroutine is resumed again.
coroutine.status(co)Returns the status of the coroutine co passed as argument. Possible values are “suspended“, “running”, “dead”, or “normal”.
coroutine.wrapCreates a new coroutine and returns a function that resumes it when called. Can be used as a simpler alternative to coroutine.create and coroutine.resume.
coroutine.runningThis method returns the object of the coroutine that is currently running, or nil if it is called from the main thread.
coroutine.isyieldableReturns a boolean indicating whether the current coroutine is yieldable. With coroutine.wrap, coroutines cannot yield, and will always return false.

The following example is implemented using coroutine.create, coroutine.resume(), coroutine.yield(), coroutine.status(), coroutine.running() and coroutine.isyieldable() methods in Lua:

Example: 

local function safeYield() if coroutine.isyieldable() then coroutine.yield("It's safe to yield now") print("coroutine.yield is executed") print("\n") else print("It's not safe to yield now") end endlocal function printCurrentCoroutine() local currentCoroutine = coroutine.running() if currentCoroutine then print("Current coroutine:", currentCoroutine) else print("Not in a coroutine") end end-- define a coroutine function local myCoroutine = coroutine.create(function() local i = 1 while i <= 3 do print("Coroutine count: "..i) printCurrentCoroutine() safeYield() i = i + 1 end end)-- start the coroutine coroutine.resume(myCoroutine)-- get the status of the coroutine local status = coroutine.status(myCoroutine) print("Coroutine status: "..status)-- resume the coroutine coroutine.resume(myCoroutine)-- get the status of the coroutine status = coroutine.status(myCoroutine) print("Coroutine status: "..status)-- resume the coroutine coroutine.resume(myCoroutine)-- get the status of the coroutine status = coroutine.status(myCoroutine) print("Coroutine status: "..status)-- resume the coroutine (should fail) coroutine.resume(myCoroutine)-- get the status of the coroutine status = coroutine.status(myCoroutine) print("Coroutine status: "..status)

Above code defines two functions, safeYield and printCurrentCoroutine, and lua coroutine function named myCoroutine. It creates a new coroutine and runs it with coroutine.resume, calling safeYield function that checks if it is safe to yield and yields the coroutine.

The code checks the status of the coroutine after each resume using coroutine.status and prints the status. The coroutine runs three iterations and then finishes, so when resumed again, it generates an error and the status is printed as “dead”.

The following example shows how to use Lua coroutine.wrap function:

Example: 

-- define a regular function that takes two arguments and returns their sum function add(a, b) return a + b end-- wrap the add function in a coroutine local co = coroutine.wrap(add)-- call the coroutine with arguments and retrieve the result local result = co(5, 4)-- print the result print(result)
If our content has made an impact on you, spread the word on social media and let others know about it!
We value your feedback.
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *