sábado, 22 de marzo de 2014

More Lua iterators


After the permutations post, I thought that we needed something like a 'take' function, that would allow us to use infinite streams safely.

local function take(n, it , param, state)
  local count = 0
  return function()
    count = count+1
    if count <= n then
      return it()
    end
    return nil
  end
end


local function take_while(fun, it , param, state)
  return function()
    if fun() then
      return it()
    end
    return nil
  end
end
 
Simple but nice.