Python中的协程如何与Lua中的协程相比?

use*_*783 16 python lua asynchronous coroutine async-await

对于在Lua协程的支持是由提供的功能在coroutine,主要是create,resumeyield.开发人员将这些协同程序描述为堆栈,一流和非对称.

协程也可在Python,或者使用增强发电机(和yield from)或在3.5版本中增加,asyncawait.

Python中的协程如何与Lua中的协程相比?它们是堆叠的,一流的还是不对称的?

为什么Python的需要如此多的结构(async def,async with,async for,异步内涵,...)的协同程序,而Lua中能为他们提供只有三个内建的功能呢?

Sun*_*day -1

我刚刚第一次看到lua,其中包括sieve.lua现场演示。它是使用协程的埃拉托斯特尼筛法的实现。我立即想到的是:这在 python 中看起来会干净得多:

#!/usr/bin/env python3

# sieve.py
# the sieve of Eratosthenes programmed with a generator functions
# typical usage: ./sieve.py 500 | column

import sys

# generate all the numbers from 2 to n
def gen(n):
    for i in range(2,n):
        yield i

# filter the numbers generated by `g', removing multiples of `p'
def filter(p, g):
    for n in g:
        if n%p !=0:
            yield n

N=int(sys.argv[1]) if len(sys.argv)>1 else 500 # from command line
x=gen(N)                     # generate primes up to N
while True:
    try:
        n = next(x)          # pick a number until done
    except StopIteration:
        break
    print(n)                 # must be a prime number
    x = filter(n, x)         # now remove its multiples
Run Code Online (Sandbox Code Playgroud)

这与问题没有太大关系,但在我的机器上,使用Python 3.4.3堆栈溢出发生在N>7500. 使用堆栈溢出已经发生sieve.lua在。Lua 5.2.3N>530

生成器对象(代表挂起的协程)可以像任何其他对象一样传递,并且内置的 next() 可以在任何地方应用到它,因此 python 中的协程是一流的。如果我错了,请纠正我。