1

Is there a function a function like xrange (of Python) in Lua, so I can do something like this:

for i in xrange(10) do
    print(i)
end

It's different from that other question, because he is looking for a condition tester, but I'm not looking for a condition tester.

wb9688
  • 179
  • 10
  • 1
    possible duplicate of [Lua For Variable In Range](http://stackoverflow.com/questions/12020574/lua-for-variable-in-range) – scrappedcola Sep 29 '15 at 14:38
  • @scrappedcola No, It's different from that other question, because he is looking for a condition tester, but I'm not looking for a condition tester. – wb9688 Sep 29 '15 at 14:42
  • 1
    the answer provides a way to obtain a range of numbers. Unless you really thing there will be a built in function in lua that dynamically stores the list, rather than creating a static list, then the `for var=2,20 do` is the answer to your question. You need to specify what features of xrange that you are looking for – scrappedcola Sep 29 '15 at 15:01
  • `function xrange(n) return string.gmatch(('.'):rep(n-1),'()') end` – Egor Skriptunoff Sep 29 '15 at 22:04

2 Answers2

2

If you want to iterate over numbers:

for i = 0,9 do
    print(i)
end

In the other way you can make your own iterator:

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

and use it: for i in range(0, 10) do print(i) end

Also you can see http://lua-users.org/wiki/RangeIterator

sisoft
  • 953
  • 10
  • 22
0
function xrange(a,b,step)
  step = step or 1
  if b == nil then a, b = 1, a end
  if step == 0 then error('ValueError: xrange() arg 3 must not be zero') end
  if a + step < a then return function() end end
  a = a - step
  return function()
           a = a + step
           if a <= b then return a end
         end
end
tonypdmtr
  • 3,037
  • 2
  • 17
  • 29