1

I want to know how to do this in Lua

Python:

for i in range(10)
 print("Hello World")
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
Epnosary
  • 11
  • 3

2 Answers2

5

Lua has a special "numeric for" loop. Two forms exist:

for i = from, to do ... end

equivalent to for i in range(from, to + 1) in Python since Python ranges have an exclusive end index, and

for i = from, to, increment do ... end

equivalent to for i in range(from, to + increment, increment) in Python.

Python's range loop allows omitting the from parameter and supplying only the (exclusive) to parameter as in your example:

for i in range(10):
    print(i)

this is not equivalent to

for i = 1, 10 do print(i) end

in Lua: Python will start at 0 and go until 9, whereas the Lua loop starts at 1 and goes until 10. If you don't need the index - and only need to many iterations - or the index is supposed to be the index into a Lua table, string or the like, you should use a loop going from 1 to 10 (both inclusive).

The proper equivalent loop to Python's for i in range(to) in Lua is

for i = 0, to - 1 do ... end

Finally, you might implement your own range iterator. This will exhibit worse performance due to function call overhead though.

function range(...)
    local n_args = select("#", ...)
    local increment = 1
    if n_args == 1 then
        from, to = 0, ...
    elseif n_args == 2 then
        from, to = ...
    elseif n_args == 3 then
        from, to, increment = ...
    else error"range requires 1-3 arguments" end

    local i = from
    return function()
        if i >= to then return end -- note: to is exclusive
        local prev_i = i
        i = i + increment
        return prev_i
    end
end

Usage is just like Python's range:

for i in range(stop) do ... end
for i in range(start, stop) do ... end
for i in range(start, stop, increment) do ... end
Luatic
  • 8,513
  • 2
  • 13
  • 34
1

It should be as follows:

for i=1,10 do print(i) end

Lua loops follow the pattern of:

for init,max/min value, increment
Greymanic
  • 116
  • 1
  • 6