lua-users home
lua-l archive

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


Hi,

Lua supports cooperative coroutines out of the box, which is great.
Unfortunately Lua lacks built-in communication primitives. To fill the
void I've implemented Go style channels in pure Lua.

Of course abstract channels without any concurrent IO aren't terribly
useful, but fortunately the code is pretty straightforward and
adapting it to your event loop shouldn't be a problem.

The code is here (~400 lines of code + ~200 of tests):
  https://github.com/majek/lua-channels/blob/master/task.lua

For example, here's Eratosthenes sieve following Russ Cox explanation:
   http://swtch.com/~rsc/thread/

Code: https://github.com/majek/lua-channels/blob/master/sieve.lua

local task = require('task')

local function counter(c)
   local i = 2
   while true do
      c:send(i)
      i = i + 1
   end
end

local function filter(p, recv_ch, send_ch)
   while true do
      local i = recv_ch:recv()
      if i % p ~= 0 then
         send_ch:send(i)
      end
   end
end

local function sieve(primes_ch)
   local c = task.Channel:new()
   task.spawn(counter, c)
   while true do
      local p, newc = c:recv(), task.Channel:new()
      primes_ch:send(p)
      task.spawn(filter, p, c, newc)
      c = newc
   end
end

local function main()
   local primes = task.Channel:new()
   task.spawn(sieve, primes)
   for i = 1, 10 do
      print(primes:recv())
   end
end

task.spawn(main)
task.scheduler()