Pythonã§ã³ã«ã¼ãã³
Luaã¯ã³ã«ã¼ãã³ãã¨ã¦ãç¹å¾´çã§ããããªã«ç¶ç¶ãªãã¸ã§ã¯ããæ±ããããè¨èªã¯ãä»ã«ããã¾ããã
http://www.lua.org/manual/5.1/manual.html#2.11
Luaã¾ã§ã¯ã ãªã§ããPythonã§ããã«è¿ããã¨ãã§ããªãããææ¦ãã¦ã¿ã¾ããã
Python2.5以ä¸ãããªãã¨ãã¡ã§ãããã¸ã§ãã¬ã¼ã¿é¢æ°ãå ¥åã¨ãã¦ä½æããããã³ã«ã¼ãã³ããã©ãããªãã¸ã§ã¯ãã§ãã
class Coroutine: def __init__(self, func): self._gen = func self._itr = None self.response = None self.alive = True def resume(self, *args): if not self.alive: raise "cannot resume dead coroutine" try: if self._itr is None: self._itr = self._gen(*args) self.response = self._itr.next() else: self.response = self._itr.send(args) return self.response except StopIteration: self.alive = False self.response = None
ã£ã¦ãããã ãããæå³ä¸æãªã®ã§ãå®ä¾ãã
# coroutine def zig_zag(msg): for i in xrange(4): print "(%s to co)" % msg, print "zig", msg = yield i print "(%s to co)" % msg, print "zag", msg = yield i # user co = Coroutine(zig_zag) i = 0 while(co.alive): print "(%s from co)" % co.resume(i) i += 1
åºåã¯ãããªæãã
(0 to co) zig (0 from co) (1 to co) zag (0 from co) (2 to co) zig (1 from co) (3 to co) zag (1 from co) (4 to co) zig (2 from co) (5 to co) zag (2 from co) (6 to co) zig (3 from co) (7 to co) zag (3 from co) (None from co)
ããã§ããã¸ã§ãã¬ã¼ã¿ããä½ãããã¤ãã¬ã¼ã¿ããã®ã¾ã¾ä½¿ãã®ã§ã¯ãªããã³ã«ã¼ãã³ã¨ãã¦ç¿»è¨³ãã¦ããã ãã§ãã
ã ãã¶Luaã£ã½ããªãã¾ããã
é¢æ°ã®ããã«ãã©ã¡ã¼ã¿ã転éããã«ã¯ã404 Not Foundã§è¿½å ãããæ©è½ãå¿ è¦ãªã®ã§ãPythonã®ãã¼ã¸ã§ã³ã¯2.5以ä¸ã«ãªã£ã¦ãã¾ãã¾ãããã³ã«ã¼ãã³ã¸ã®ãã©ã¡ã¼ã¿å ¥åãå¿ è¦ãªããã°ã2.4以ä¸ã§ãä¼¼ããããªãã¨ã¯å¯è½ããããã¾ããã
ãã ãããã³ã«ã¼ãã³ããã¹ããããã¨ããåé¡ã§ããLuaã ã¨yieldãé¢æ°ãªã®ã§ãé¢æ°ã®ãã¹ãã¨ãã¦åç´ã«ãªãã¡ã¯ã¿ãªã³ã°ã§ãã¾ããããPythonã®yieldã¯ããã®é¢æ°å ã§ã®ã¿æå¹ãªãæ§æãã§ãã
ã³ã«ã¼ãã³ãã¹ãã¯ãããªæãã
def main_flow(): print "main start" yield # This way is lessor than Lua co = Coroutine(sub_flow) while(co.alive): yield co.resume() print "main end" def sub_flow(): print "sub start" yield for i in xrange(10): print "sub %d" % i yield print "sub end" # execute step by step with interval import time co = Coroutine(main_flow) while(co.alive): co.resume() time.sleep(0.5)
main_flowãsub_flowã使ãã¨ããåãªãé¢æ°å¼ã³åºãã§ã¯ãªããããµãã³ã«ã¼ãã³ãä½æãã¦è»¢éãããå¿ è¦ãããã¾ãããã¾ããLuaã«ã¯åã°ãªããã©ãããã¾ã§ã²ã©ããããããªãã§ãããã³ã«ã¼ãã³ã®å»ã¿å¹ ã£ã¦ããããªã«æ·±ãããå¿ è¦ã¯ãªãã ãããã