1 Symmetric Coroutine
Lua支持asymmetric coroutine。对于symmetric coroutine,名为Coroutines in Lua的一篇论文,提供了如下的解决方案:
coro = {} coro.main = function() end coro.current = coro.main function coro.create(f) return coroutine.wrap(function(val) return nil, f(val) end) end function coro.transfer(k, val) if coro.current ~= coro.main then return coroutine.yield(k, val) else while k do coro.current = k if k == coro.main then return val end k, val = k(val) end error("coroutine ended without transfering control...") end end
代码虽然不长,但是十分精致。通过yield/resume,以及一个dipatching循环,巧妙地实现了symmetric coroutine。此外在Revisiting Coroutines论文中,甚至用asymmetric coroutine实现了one-shot continuation。
2 Reference
Coroutines in Lua Ana L´ucia de Moura , Noemi Rodriguez , Roberto Ierusalimschy
Revisiting Coroutines Ana L´ucia de Moura and Roberto Ierusalimschy