Stream module for Lua

“Be not afraid of greatness: some are born great, some achieve greatness and some have greatness thrust upon them”.
– (Shakespeare, W., Twelfth Night, Quote Act II, Scene V).

“Some men are born mediocre, some men achieve mediocrity, and some men have mediocrity thrust upon them. With Major Major it had been all three”.
– (Heller, J., Catch-22, Quote Page 94 (paperback)).

“Some languages are born lazy, some languages achieve laziness, and some languages have laziness thrust upon them”.
– (Salim, M., unpublished)

So you can probably guess what this is about. A stream library for Lua, that allows you to do things like running the Sieve of Eratosthenes without specifying an upper bound, lazily filtering the set of all positive integers as you go along.

Witness the use of the library:


function ints(n)
   return {
      head = function () return n end,
      tail = function () return ints(n+1) end }

function primes (sints)
   local curprime = false
   local tailthunk = false
   local fhead =
      function ()
	 if curprime then return curprime
	    curprime = sints.head()
	    tailthunk = sints.tail
	    return curprime
   local ftail =
      function ()
	 if (not tailthunk) then
	 return primes(
		 stream.filter(function(n) return not (n%curprime == 0) end,
			       tailthunk() ))
   return {head=fhead, tail=ftail}

-- print the first 100 primes
stream.print(100, primes(ints(2)))

A stream is a table containing a head and a tail; both are thunks, so you call them with no arguments to obtain the value. Note the caching that avoids recomputation, similar caching is done in the functions provided by the stream library (like stream.filter)

Code available on

And some benchmarks:

Lua Haskell

The Haskell code was run using GHC’s ‘runhaskell’, which does not precompile the code, to be fair to Lua which is interpreted. Not bad when put up against a language that is lazy by design (and thus optimized for it)! Timing taken using the ‘time’ utility on an Intel Core 2 Duo 1.66 GHz laptop which was mostly idle.


One response to “Stream module for Lua