Coroutine yielding is a powerful feature in Lua that allows for cooperative multitasking. It enables a coroutine to pause its execution and return control to the calling function, only to resume later from where it left off.
In Lua, the coroutine.yield()
function is used to suspend the execution of a running coroutine. When a coroutine yields, it returns any values passed to yield()
to the coroutine.resume() call that started it.
coroutine.yield([...])
The ellipsis (...) represents optional values that can be passed back to the resuming function.
When a coroutine yields:
local co = coroutine.create(function()
for i = 1, 3 do
print("Coroutine", i)
coroutine.yield()
end
end)
coroutine.resume(co) -- Prints: Coroutine 1
coroutine.resume(co) -- Prints: Coroutine 2
coroutine.resume(co) -- Prints: Coroutine 3
coroutine.resume(co) -- Returns false (coroutine has ended)
In this example, the coroutine yields after each iteration, allowing the main program to control when to continue the coroutine's execution.
Coroutine yielding can also be used to pass values between the coroutine and the main program. This enables powerful communication patterns.
local co = coroutine.create(function()
local x = coroutine.yield("First yield")
print("Received:", x)
return "Coroutine finished"
end)
local status, value = coroutine.resume(co)
print("Yielded value:", value) -- Prints: Yielded value: First yield
status, value = coroutine.resume(co, "Hello from main")
print("Return value:", value) -- Prints: Return value: Coroutine finished
Coroutine yielding is a fundamental aspect of Lua's Lua Coroutine Basics. It provides a flexible way to implement cooperative multitasking and manage complex control flows in your Lua programs. By mastering yielding, you can create more efficient and responsive applications, especially in scenarios involving asynchronous operations or complex state management.