Repeating with loops
Run the same code many times without writing it many times.
Your Lua code runs inside your browser tab. Nothing to install.
Counting with a loop
A loop runs the same block of code several times.
for i = 1, 3 do runs the block once for each number from 1 to 3, with the number in i. The last number is included. The block finishes at end.
The loop variable holds a different number on each pass.
for i = 1, 3 do
print(i)
endYour turn: counting
Count a little further than the example does.
Practice task
Use a loop to print the numbers from 1 to 5, one on each line.
Your answer is run and checked in the lesson. Create a free account to try it.
Building up a result
A loop is often used to build up one answer. Create a variable before the loop, change it inside the loop, and use it after the loop.
Lua has no +=. To add to a total, write total = total + i.
The print in the example comes after the loop has closed, so it runs once, at the end.
local total = 0
for i = 1, 4 do
total = total + i
end
print(total)Repeating while something is true
A while loop repeats for as long as its condition is true. Its block starts at do and finishes at end.
Something inside the loop must change so that the condition becomes false. If nothing does, the loop never ends.
The example halves a number until it drops below 10.
local n = 80
while n >= 10 do
print(n)
n = n // 2
endYour turn: a total
Combine a loop with a running total.
Practice task
Use a loop to add the numbers from 1 to 10, then print the total once.
Your answer is run and checked in the lesson. Create a free account to try it.