按照书上码了下,但运行有问题,暂时不知道原因:
function send (x)
coroutine.yield(x)
end function producer()
return coroutine.create( function ()
while true do
local x = 1
send(x)
end
end)
end function receive(prod)
local status, value = coroutine.resume(prod)
return value
end function filter (prod)
return coroutine.create(function()
a = {1,2,3,4,5,6,7,8,9,10}
for line , k in pairs(a) do
local x = receive(prod)
x = string.format("%5d %s",line,x)
send(x)
end
end)
end function consumer (prod)
while true do
local x = receive(prod)
print(x)
end
end consumer(filter(producer()))
之后再来细看,主要是 producter-consumer模型。