0Pricing
Lua Academy · Lesson

Numeric for Loop

Iterate over numeric ranges with the for i=start,limit,step syntax.

Numeric for Syntax

Lua's numeric for loop has the form for var = start, limit, step do. The step defaults to 1 if omitted. The loop variable is local to the loop body and cannot be modified inside. The limit and step are evaluated once before the loop starts.

-- Count 1 to 5
for i = 1, 5 do
  io.write(i .. " ")
end
print()   -- 1 2 3 4 5

-- Count with step 2
for i = 1, 10, 2 do
  io.write(i .. " ")
end
print()   -- 1 3 5 7 9

Countdown with Negative Step

Use a negative step to count downward. The loop continues as long as var >= limit (when step is negative). If the start is already less than the limit with a negative step, the loop body never executes.

for i = 10, 1, -1 do
  io.write(i .. " ")
end
print()
-- 10 9 8 7 6 5 4 3 2 1

-- Step -2
for i = 10, 0, -2 do
  io.write(i .. " ")
end
print()
-- 10 8 6 4 2 0

All lessons in this course

  1. if, elseif and else Statements
  2. while and repeat-until Loops
  3. Numeric for Loop
  4. Generic for and break
← Back to Lua Academy