コルーチン

ところで Lua の言語的な特徴は「なんでもテーブル」ということかと思ったら、あとコルーチンもあることを知る。

コルーチンを作るのには、

  1. 関数を用意し、
  2. coroutine.create でコルーチン化し、
  3. coroutine.resume で実行、
  4. コルーチン内では coroutine.yield で実行を中断し、呼出し元に戻る

という手順(?)になる。

function co(x)
  local v
  while true do
    x = x + 1
    v = coroutine.yield(x)
    print("coroutine\n", x, v)
  end
end

f = coroutine.create(co)
print("main routine\n", coroutine.resume(f, 0))
print("main routine\n", coroutine.resume(f, 1))
print("main routine\n", coroutine.resume(f, 2))
print("main routine\n", coroutine.resume(f, 3))

yield でコルーチンは停止し、 resume に戻る。 resume はコルーチンが正常終了、または yield すると true が返るが、二番目の要素以降に return の返り値、ないしは yield の引数が与えられる。また、 yield したものを resume すると、そのときの引数は yield の返り値になる。ちなみに、終了しちゃったコルーチンを resume するとエラーになる。

といったところか。