Loops

A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code "inside" the loop (the body of the loop) is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.

The for-loop
for var = startValue, endValue, increment do    ... end The for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly. The increment is optional, per default one, and can be negative. for x = 1, 100, 5 do    print(x) end -- 1, 6, 11, 16, 21, ..., 91, 96 for x = 0, 100, 5 do    print(x) end -- 0, 5, 10, 15, 20, ..., 90, 95, 100 The variable never exceeds the endValue.

Pairs and ipairs
While Lua does not have a foreach method, it has the for .. in .. loop, including the pairs and ipairs (= indexed pairs) functions. local k = {"a", "b", "d", "f"} k.hello = "e" k["greetings"] = "c" for a, b in ipairs(k) do print(b) end -- a, b, d, f (in this order) for a, b in pairs(k) do print(b) end -- a, b, d, f (in this order), e, c (not necessarily in this order)

The while-loop
The while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement. The code will be executed as long the statement in the condition is true. Since Lua runs on one thread mostly, while loops shouldn't be indefinitely. while statement do    ... end

The repeat-until-loop
The repeat-until statement repeats its body until its condition is true. The test is done after the body, so the body is always executed at least once. repeat ... until statement