co = coroutine.create(
function ()
for i=1, 10 do
print("co", i)
coroutine.yield()
end
end
)
coroutine.resume(co) ---> co 1 (coroutine.yield()まで実行され、suspendedに戻される)
coroutine.resume(co) ---> co 2 (coroutine.yield()まで実行され、suspendedに戻される)
コルーチンが実行に失敗した場合には、
print(coroutine.resume(co)) ---> false cannot resume dead coroutine というように第1返値にfalse, 第2返値にエラーメッセージとなる。
function recieve (prod)
local status, value = coroutine.resume(prod)
return value
end
function send (x)
coroutine.yield(x)
end
function producer ()
return coroutine.create(function ()
while true do
local x = io.read()
send(x)
end
end )
end
function consumer(prod)
while true do
local x = recieve(prod)
io.write(x, "\n")
end
end
consumer(producer())
function itr()
local co = coroutine.create(function ()
local i = 1
while true do
coroutine.yield(i)
i = i + 2
end
end)
return function ()
local state, res = coroutine.resume(co)
return res
end
end
for i in itr() do
print(i)
if i > 10 then break end
end
local itr = coroutine.wrap(function ()
local i = 1
while true do
coroutine.yield(i)
i = i + 2
end
end)
for i in itr do
print(i)
if i > 10 then break end
end
これらのfor .. in の挙動を理解するためには、 イタレータの項目の「for ... in の展開」を知っておく必要がある。