🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Nested Loops

A nested loop is a loop placed inside another loop. For each single pass of the outer loop, the inner loop runs all of its passes.

A 3 by 3 star grid

The outer loop picks a row. The inner loop builds that row as one string, then the row prints.

for r = 1, 3 do
  local row = ""
  for c = 1, 3 do
    row = row .. "*"
    if c < 3 then
      row = row .. " "
    end
  end
  print(row)
end

Coordinates in order

The inner count runs 1 to 3 for row 1 first. Only then does the outer loop move to row 2.

for r = 1, 2 do
  for c = 1, 3 do
    print(string.format("(%d,%d)", r, c))
  end
end

A small addition grid

Each row adds one fixed number to 1, 2, and 3. The %2d format pads each sum to the same width.

for a = 1, 3 do
  local row = ""
  for b = 1, 3 do
    row = row .. string.format("%2d", a + b)
  end
  print(row)
end

Example

for a = 1, 4 do
  local row = ""
  for b = 1, 4 do
    if b > 1 then
      row = row .. " "
    end
    row = row .. string.format("%2d", a * b)
  end
  print(row)
end

Key points

  • Nested loop: the inner loop sits inside the body of the outer loop.
  • Full inner run: the inner loop finishes before the outer loop moves on.
  • Row building: joining one row into a string lets you print a whole row at once.
  • Total passes: multiply the outer count by the inner count to get the inner body count.
  • Small grids: keep rows and columns small while you learn the pattern.

In this example, the outer loop picks the row number a from 1 to 4. The inner loop runs b from 1 to 4 and joins each product into the row string, padded with %2d so the columns line up. Each finished row prints once, giving a 4 by 4 multiplication grid.

Note

each loop needs its own end, so a nested loop has two end lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

An outer loop runs 3 times and an inner loop runs 4 times for each outer pass. How many times does the inner body run in total?