Producer-Consumer Pattern
Implement a producer-consumer pipeline using coroutines.
The Pattern Explained
The producer-consumer pattern with coroutines: the producer generates data and yields each item; the consumer receives items one at a time. Neither needs to know the other's implementation — they communicate through yield/resume. This decouples data generation from data processing.
local function makeProducer(items)
return coroutine.create(function()
for _, item in ipairs(items) do
coroutine.yield(item)
end
end)
end
local function consume(producer)
while true do
local ok, item = coroutine.resume(producer)
if not ok or item == nil then break end
print("Processing:", item)
end
end
consume(makeProducer({10, 20, 30, 40}))Infinite Producer
A producer coroutine can yield an infinite sequence. The consumer controls when to stop. This is perfect for streaming data sources: sensor readings, log events, generated sequences.
local function primes()
return coroutine.wrap(function()
local function isPrime(n)
if n<2 then return false end
for i=2, math.floor(math.sqrt(n)) do
if n%i==0 then return false end
end
return true
end
local n = 2
while true do
if isPrime(n) then coroutine.yield(n) end
n = n + 1
end
end)
end
local gen = primes()
for i = 1, 10 do
io.write(gen() .. " ")
end
print() -- 2 3 5 7 11 13 17 19 23 29All lessons in this course
- Creating Coroutines
- resume and yield
- Coroutine Status
- Producer-Consumer Pattern