-- the sieve of of Eratosthenes programmed with coroutines-- typical usage: lua -e N=1000 sieve.lua | column-- generate all the numbers from 2 to nfunctiongen(n)returncoroutine.wrap(function()fori=2,ndocoroutine.yield(i)endend)end-- filter the numbers generated by `g', removing multiples of `p'functionfilter(p,g)returncoroutine.wrap(function()while1dolocaln=g()ifn==nilthenreturnendifmath.mod(n,p)~=0thencoroutine.yield(n)endendend)endN=Nor1000-- from command linex=gen(N)-- generate primes up to Nwhile1dolocaln=x()-- pick a number until doneifn==nilthenbreakendprint(n)-- must be a prime numberx=filter(n,x)-- now remove its multiplesend