Lua Academy · Lesson

Numeric for Loop

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

Lesson 3 of 412 steps

Numeric for Loop is a free Lua Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

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

Loop Variable is Local

The loop control variable (i) is automatically local. You cannot change its value inside the loop — Lua ignores assignments to the loop variable. To track iterations differently, use a separate local variable.

for i = 1, 5 do
  -- i is read-only inside the loop
  -- i = i + 10  -- this creates a new global i, not the loop var
  print(i)  -- always 1, 2, 3, 4, 5 as expected
end
-- i is nil here (it was local to the loop)
print(i)  -- nil (or whatever global i was)

Iterating Arrays

The most common use of the numeric for is iterating arrays by index. Use #arr as the limit. Unlike ipairs, this form lets you control step size and iterate in reverse, and it's slightly faster for dense arrays.

local fruits = {"apple", "banana", "cherry", "date"}

for i = 1, #fruits do
  print(i, fruits[i])
end
-- 1  apple
-- 2  banana
-- 3  cherry
-- 4  date

Summing with for

Numeric for loops are ideal for accumulating over arrays. The pattern is always the same: initialize a result variable before the loop, update it inside, and use it after.

local values = {10, 20, 30, 40, 50}
local total = 0

for i = 1, #values do
  total = total + values[i]
end

print("Total:", total)    -- 150
print("Count:", #values)  -- 5
print("Mean:", total / #values)  -- 30

Nested Numeric for

Nest two numeric for loops for 2D operations like matrix traversal, table of tables, or generating coordinate pairs. The outer loop rows, the inner loop columns — each iteration accesses one cell.

local rows, cols = 3, 4

for r = 1, rows do
  for c = 1, cols do
    io.write(string.format("%2d ", r * c))
  end
  print()
end
--  1  2  3  4
--  2  4  6  8
--  3  6  9 12

Float Steps

The step and limits can be floating-point numbers, though this can introduce precision errors. For exact iteration counts, stick to integers. If you must use floats, be aware that the loop count is computed as floor((limit - start) / step) + 1.

-- Float step
for x = 0.0, 1.0, 0.25 do
  io.write(x .. " ")
end
print()
-- 0.0  0.25  0.5  0.75  1.0

-- Prefer integer math when possible
for i = 0, 4 do
  local x = i * 0.25
  io.write(x .. " ")
end

Building a Result Table

A numeric for loop is the standard way to build a new table from existing data. Create an empty table, then use the loop to fill it by index.

local source = {1, 2, 3, 4, 5}
local squares = {}

for i = 1, #source do
  squares[i] = source[i] ^ 2
end

for i = 1, #squares do
  print(squares[i])   -- 1, 4, 9, 16, 25
end

break in Numeric for

You can exit a numeric for early with break. Execution jumps to the statement after end. This is useful for linear search: iterate until the target is found, then break.

local data = {5, 3, 8, 1, 9, 2, 7}
local target = 9
local foundAt = nil

for i = 1, #data do
  if data[i] == target then
    foundAt = i
    break
  end
end

if foundAt then
  print("Found at index " .. foundAt)  -- 5
else
  print("Not found")
end

Loop Count Calculation

The number of iterations of for i = start, limit, step is max(0, floor((limit - start) / step) + 1). Understanding this prevents off-by-one errors. When step is 1, the count is simply limit - start + 1.

-- How many iterations?
local count = 0
for i = 1, 10, 3 do
  count = count + 1
end
print(count)   -- 4  (i = 1, 4, 7, 10)

count = 0
for i = 5, 1 do   -- step=1 but start > limit
  count = count + 1
end
print(count)   -- 0 (no iterations)

Quick Check

What does for i = 10, 1, -3 do iterate over?

Recap: Numeric for

Summary:

  • for i = start, limit, step do — step defaults to 1
  • Negative step for countdown
  • Loop variable is automatically local and read-only
  • Limit and step evaluated once before loop starts
  • break exits early
  • Standard pattern: build result tables, search arrays, accumulate sums
Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Numeric for Loop” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Numeric for Loop”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “Numeric for Loop”?

Iterate over numeric ranges with the for i=start,limit,step syntax. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Numeric for Loop” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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