Lua by Example: Coroutines
Coroutines enable collaborative multitasking. This example shows how to create, resume, and yield from a coroutine.
Code
local co = coroutine.create(function()
for i = 1, 3 do
print("Coroutine working: " .. i)
-- Pause execution and return value
coroutine.yield(i)
end
return "Done"
end)
print("Main: Status is " .. coroutine.status(co))
-- Resume execution
local success, value = coroutine.resume(co)
print("Main: Yielded " .. value)
success, value = coroutine.resume(co)
print("Main: Yielded " .. value)
success, value = coroutine.resume(co)
print("Main: Yielded " .. value)
-- Final resume to finish
success, value = coroutine.resume(co)
print("Main: Finished with " .. value)Explanation
Coroutines in Lua are collaborative threads of execution. Unlike OS threads, they are managed by Lua and are non-preemptive; a coroutine runs until it explicitly yields control back to the caller. This makes them deterministic and avoids complex race conditions associated with preemptive multithreading.
You create a coroutine with coroutine.create, which takes a function. It starts in a suspended state. To run it, you call coroutine.resume. Inside the coroutine, coroutine.yield pauses execution and can pass values back to the resume call. The next time you call resume, execution continues right after the yield.
Coroutines are powerful tools for implementing iterators, state machines, and asynchronous I/O systems (like in the LÖVE game engine or OpenResty web server). They allow you to write code that looks synchronous and linear, even though it pauses and resumes over time.
Code Breakdown
coroutine.yield(i) pauses the function and returns i to the main thread.coroutine.resume(co) switches control to the coroutine. It returns true (if no error) and any yielded values.
