Web Analytics

Loops in Lua

Beginner ~25 min read

Loops allow you to repeat code multiple times, making your programs more efficient and powerful. Lua provides several types of loops: while, repeat-until, and for (both numeric and generic). Each has its own use case and advantages. Let's explore them all!

The while Loop

The while loop repeats code as long as a condition is true:

local count = 1

while count <= 5 do
    print("Count:", count)
    count = count + 1
end

-- Output:
-- Count: 1
-- Count: 2
-- Count: 3
-- Count: 4
-- Count: 5
Syntax:
  • Start with while followed by a condition
  • Use do after the condition
  • Write the code to repeat
  • End with end
Output
Click Run to execute your code
Warning: Make sure your loop condition eventually becomes false, or you'll create an infinite loop! Always update the loop variable inside the loop.

The repeat-until Loop

The repeat-until loop executes at least once, then checks the condition:

local count = 1

repeat
    print("Count:", count)
    count = count + 1
until count > 5

-- Output is the same as while loop
-- But the code runs at least once!
Tip: Use repeat-until when you need the loop body to execute at least once, like validating user input or menu systems.
Output
Click Run to execute your code

while vs repeat-until

Feature while repeat-until
Condition check Before execution After execution
Minimum executions 0 (may not run) 1 (always runs once)
Condition Continue while true Stop when true

The Numeric for Loop

The numeric for loop is perfect for counting:

-- Count from 1 to 5
for i = 1, 5 do
    print(i)
end

-- Count from 1 to 10 by 2s
for i = 1, 10, 2 do
    print(i)  -- 1, 3, 5, 7, 9
end

-- Count backwards
for i = 5, 1, -1 do
    print(i)  -- 5, 4, 3, 2, 1
end
Syntax: for variable = start, stop, step do
  • start: Starting value
  • stop: Ending value (inclusive)
  • step: Increment (default is 1)
Output
Click Run to execute your code
Best Practice: The loop variable (i) is local to the loop and cannot be modified inside the loop body. This prevents common errors!

The Generic for Loop

The generic for loop iterates over collections using iterators:

Iterating Over Arrays

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

-- Using ipairs for arrays
for index, value in ipairs(fruits) do
    print(index, value)
end

-- Output:
-- 1    apple
-- 2    banana
-- 3    cherry

Iterating Over Tables

local person = {
    name = "Alice",
    age = 25,
    city = "New York"
}

-- Using pairs for tables
for key, value in pairs(person) do
    print(key, value)
end

-- Output:
-- name    Alice
-- age     25
-- city    New York
Output
Click Run to execute your code

ipairs vs pairs

Iterator Use For Order
ipairs Arrays (sequential tables) Guaranteed (1, 2, 3...)
pairs All tables (any keys) Not guaranteed
Tip: Use ipairs for arrays and pairs for hash tables. ipairs stops at the first nil value!

The break Statement

Use break to exit a loop early:

-- Find first even number
for i = 1, 10 do
    if i % 2 == 0 then
        print("First even number:", i)
        break  -- Exit the loop
    end
end

-- Search in array
local numbers = {1, 3, 5, 8, 9, 11}
for i, num in ipairs(numbers) do
    if num % 2 == 0 then
        print("Found even number at index", i)
        break
    end
end
Output
Click Run to execute your code
Note: Lua does NOT have a continue statement. To skip to the next iteration, use if statements or restructure your code.

Nested Loops

You can put loops inside other loops:

-- Multiplication table
for i = 1, 5 do
    for j = 1, 5 do
        print(i .. " x " .. j .. " = " .. (i * j))
    end
end

-- 2D grid
for row = 1, 3 do
    for col = 1, 3 do
        print("(" .. row .. "," .. col .. ")")
    end
end
Output
Click Run to execute your code

Common Loop Patterns

Sum of Numbers

local sum = 0
for i = 1, 10 do
    sum = sum + i
end
print("Sum:", sum)  -- 55

Finding Maximum

local numbers = {5, 2, 9, 1, 7}
local max = numbers[1]

for i = 2, #numbers do
    if numbers[i] > max then
        max = numbers[i]
    end
end
print("Maximum:", max)  -- 9

Filtering

local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local evens = {}

for i, num in ipairs(numbers) do
    if num % 2 == 0 then
        table.insert(evens, num)
    end
end
-- evens = {2, 4, 6, 8, 10}

Practice Exercise

Try these loop challenges:

Output
Click Run to execute your code

Summary

In this lesson, you learned:

  • while loops: repeat while condition is true
  • repeat-until loops: execute at least once
  • Numeric for loops: count from start to stop
  • Generic for loops: iterate with ipairs and pairs
  • break statement to exit loops early
  • Nested loops for multi-dimensional iteration
  • Common patterns: sum, max, filtering

What's Next?

Congratulations on completing Module 2! You now understand operators, strings, conditionals, and loopsβ€”the building blocks of programming. Next, we'll dive into functions, one of Lua's most powerful features. You'll learn how to write reusable code, work with closures, and master functional programming concepts. Let's continue! πŸš€