Range Iterator

lua-users home
wiki

The range function below returns an iterator that can be used in for loops instead of the basic for i=i,j,k do end syntax. It can be used for example when the two or three parameters of the basic for loop are returned by another function. -- JeromeVuarand

function range(from, to, step)
  step = step or 1
  return function(_, lastvalue)
    local nextvalue = lastvalue + step
    if step > 0 and nextvalue <= to or step < 0 and nextvalue >= to or
       step == 0
    then
      return nextvalue
    end
  end, nil, from - step
end

Example use:

function f() return 10, 0, -1 end

for i in range(f()) do
  print(i)
end

Conditionals may also be moved out of the functions: --DavidManura

function range(from, to, step)
  step = step or 1
  local f =
    step > 0 and
      function(_, lastvalue)
        local nextvalue = lastvalue + step
        if nextvalue <= to then return nextvalue end
      end or
    step < 0 and
      function(_, lastvalue)
        local nextvalue = lastvalue + step
        if nextvalue >= to then return nextvalue end
      end or
      function(_, lastvalue) return lastvalue end
  return f, nil, from - step
end

FindPage · RecentChanges · preferences
edit · history
Last edited September 20, 2008 1:02 am GMT (diff)