This is the consumer-producer , producer as coroutine and consumer as main thread:
function receive (prod) local status, value = coroutine.resume(prod) return valueend function send (x) coroutine.yield(x) end function producer () return coroutine.create(function () while true do local x = io.read() -- produce new value send(x) end end) end function filter (prod) return coroutine.create(function () for line = 1, math.huge do local x = receive(prod) -- get new value x = string.format("%5d %s", line, x) send(x) -- send it to consumer end end) end function consumer (prod) while true do local x = receive(prod) io.write(x, "\n") end end -- get new value -- consume new value consumer(filter(producer()))
and here is my answer bt is not running as expected:
function receive (x) coroutine.yield(x) end function send (cons, x) local status, value = coroutine.resume(cons, x) return value end function producer (cons) while true do local x = io.read() -- produce new value send(cons, x) end end function filter (cons) return coroutine.create(function (x) for line = 1, math.huge do local _, x = receive(x) -- get new value x = string.format("%5d %s", line, x) send(cons, x) -- send it to consumer end end) end function consumer () return coroutine.create(function(x) while true do local x = receive(x) io.write(x, "\n") end end) end -- get new value -- consume new value producer(filter(consumer()))
Thing is while getting into local x = receive(x) into filter() function, then it is going again to producer() waiting for new input wthout formating x input.Any suggestion? I do not want to change the initial way was implemented, meaning the recieve() bound into the consumer() and send() bound into reciever().