Functions and loops, lesson 14
for loops
Goal: Repeat code a set number of times.
about 5 min4 practice exercises
A loop repeats code. A for loop repeats it a set number of times.
for i = 1, 3 do
print("Coin " .. i)
end
This prints Coin 1, Coin 2, Coin 3. The variable i starts at 1 and goes up by 1 each time, and the loop includes the end value.
A third number sets the step. Use a negative step to count down:
for seconds = 3, 1, -1 do
print(seconds)
end
print("Go!")
Loops are how you avoid writing the same line many times:
local total = 0
for i = 1, 4 do
total += 5
end
print(total) -- 20
The loop variable only exists inside the loop, like any other local in a block.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.