Lua イテレータをコルーチンで実装する。
これはなんか Ruby と似た感じで実装できる。
local itr = coroutine.wrap(function ()
local i = 1
while true do
coroutine.yield(i)
i = i + 1
end
end)
for i in itr do
print(i)
if i > 10 then break end
endfor in にはイテレータ関数を与える。coroutine.wrap はファンクションを与えるとコルーチン (thread) を生成してそれを resume する関数を返す。
yield の引数が呼び出し元に返って、in の前の変数に代入される。(多値かえして多重代入もできる)