Loops
A chunk of code can be repeated multiple times by using a loop. Lua provides three types of loop, the while
, repeat
, and for
loops. Each loop type will be covered in depth, but the rest of the book will mainly use the for loop.
while loops
Syntactically, a while loop starts with the while keyword, followed by a Boolean condition and a do
/end
chunk. The loop will keep executing the chunk of code so long as the Boolean condition evaluates to true
:
x = 10 -- Initialize a "control" variable while x > 0 do -- Boolean condition: x > 0 print ("hello, world") x = x - 1 -- Decrement the "control" variable end
Infinite loops
One of the dangers of loops is an infinite loop. You get into an infinite loop when the condition of the loop never evaluates to false. Because the condition keeps being true
, the loop goes on forever. The following code snippet demonstrates a simple infinite loop:
while true do print ("forever") end
A more real-life example of an infinite loop would look like...