示例工程 21-coroutines
21-coroutines/01-producer-consumer/main.lua
-- @runtimes lua54 luajit
--- 演示:create/resume/yield 的生产者-消费者。
local M = {}
local function producer()
for i = 1, 3 do
coroutine.yield(i * 10)
end
return "done"
end
--- @return table { values = table, final = string }
function M.run(log)
log = log or print
local co = coroutine.create(producer)
local values = {}
while true do
local ok, value = coroutine.resume(co)
assert(ok, value)
if coroutine.status(co) == "dead" then
log(("final=%s"):format(tostring(value)))
return { values = values, final = value }
end
values[#values + 1] = value
end
end
if not ... then
M.run()
end
return M