Symmentric Coroutine in Lua

1102 단어
Symmentric Coroutine in Lua
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 IerusalimschyRevisiting Coroutines Ana L´ucia de Moura and Roberto Ierusalimschy

좋은 웹페이지 즐겨찾기