lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> >I am
> >interested in concurrent execution of multiple scripts within a LUA
state,
> >cooperative 'multitasking' that is.
> 
> This is implemented in Lua 5.0w0.
> Here is an example program by Roberto that finds primes. Sorry for the
> comments in Portuguese.

It work fine on my box. I translated the comments using Google, but I still
don't understand how this work, it is black magic for me :-)
I will study carefully the upcoming manual...

-- Co-routine to generate all the numbers from 2 to n
function gen (n)
  return coroutine.create(function ()
      for i = 2, n do coroutine.yield(i) end
    end)
end

-- Co-routine that filters the numbers generated by 'g', taking off the
multiples of 'p'
function filter (p, g)
  return coroutine.create(function ()
      while 1 do
        local n = g()
        if n == nil then return end
        if math.mod(n, p) ~= 0 then coroutine.yield(n) end
        end
    end)
end

x = gen(1000) -- Initial generator
while 1 do
  local n = x() -- It catches a number
  if n == nil then break end -- Finished?
  print(n) -- The number is a prime
  x = filter(n, x) -- It takes off its multiples
end

Note:
add "print(2)" before x = gen(1000), replace the for loop in g by:
for i = 3, n, 2 do coroutine.yield(i) end
and it works too... It seems not faster though.

Regards.

-- 
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--

GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net