-- the sieve of of Eratosthenes programmed with coroutines1-- typical usage: lua -e N=1000 sieve.lua | column23-- generate all the numbers from 2 to n4function gen (n)5return coroutine.wrap(function ()6for i=2,n do coroutine.yield(i) end7end)8end910-- filter the numbers generated by `g', removing multiples of `p'11function filter (p, g)12return coroutine.wrap(function ()13while 1 do14local n = g()15if n == nil then return end16if math.mod(n, p) ~= 0 then coroutine.yield(n) end17end18end)19end2021N=N or 1000 -- from command line22x = gen(N) -- generate primes up to N23while 1 do24local n = x() -- pick a number until done25if n == nil then break end26print(n) -- must be a prime number27x = filter(n, x) -- now remove its multiples28end293031