BudiBadu Logo
Samplebadu

Lua by Example: Loops

Lua 5.4

Lua provides standard loop structures. This sample demonstrates `while`, `repeat-until`, and numeric/generic `for` loops.

Code

-- While loop
local i = 1
while i <= 3 do
    print("While: " .. i)
    i = i + 1
end

-- Repeat-Until (do-while)
local j = 1
repeat
    print("Repeat: " .. j)
    j = j + 1
until j > 3

-- Numeric For loop
-- start, stop, step (default 1)
for k = 1, 5, 2 do
    print("For: " .. k)
end

-- Generic For loop (iterating a table)
local days = {"Mon", "Tue", "Wed"}
for index, day in ipairs(days) do
    print(index, day)
end

Explanation

Lua supports the standard set of control structures for looping. The while loop continues as long as the condition is true. The repeat-until loop is similar to a do-while loop in other languages; the body is executed at least once, and the condition is checked at the end. Uniquely, the scope of a local variable declared inside the repeat block extends to the until condition.

The for loop comes in two flavors: numeric and generic. The numeric for loop for var = start, stop, step do runs a counter. The control variable is automatically local to the loop body and cannot be modified inside the loop. The step is optional and defaults to 1.

The generic for loop for ... in iterator do is used to traverse collections. It relies on iterator functions like pairs (for all keys) or ipairs (for numeric indices). You can also write your own stateless or stateful iterators to traverse custom data structures.

Code Breakdown

12
until j > 3 checks the condition after the block executes. The loop stops when this becomes true.
16
for k = 1, 5, 2 counts 1, 3, 5. The loop terminates when k exceeds 5.