7 Loops
Hasan Malik and Rutwa Engineer
Learning Objectives
- Learn about the need for loops
- Learn about for loops
- Learn about while loops
- Learn how to avoid infinite while loops
- Learn about nested loops
- Learn about breaks and continues
Introduction
What are Loops?
Loops are programming structures used to repeat a block of code multiple times, either for a specific number of iterations or until a particular condition is met. They help automate repetitive tasks, making programs more efficient and less error-prone.
For example, imagine a factory assembly line where a machine places caps on bottles. Instead of having a worker manually cap each bottle, the machine repeats the same task for every bottle on the line. Loops work like this machine, performing repetitive actions automatically.
Why Are Loops Useful?
Loops reduce redundant code by repeating instructions instead of writing them multiple times. Later on, they will help us handle complex tasks like iterating over lists, spawning objects, or animating characters. Loops make our code shorter, more efficient, and simpler to understand.
For Loops
For loops are used when you know how many times you want to repeat an action.
The basic structure of a for loop in Lua includes the initializer, condition, and incrementer.
The Basic Structure of a For Loop
for variable = start_value, end_value, step_value do
--code to repeat
end
variable: this is often named i (short for “index”), and acts as the loop control variable
start_value: The starting value of the loop control variable.
end_value: The value at which the loop will stop executing. The loop runs as long as the variable is less than or equal to this value.
step_value (optional): How much the variable changes each iteration (default is 1 if omitted)
Example: Counting Upwards
In this example, the loop starts at 1, and counts by 1 step until it reaches 5. In each iteration, the print function is executed.
for i=1, 5 do
print("Hello, World!")
end
—
Output:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Example: Counting Backwards
In Lua, you can count backwards using a negative step value.
for i=5, 1, -1 do
print("Countdown: " .. i)
end
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Example: Spawning Objects in Roblox
This creates 10 blocks spaced 5 units apart.
for i=1, 10 do
local part = Instance.new("Part")
part.Position = Vector3.new(i*5, 0, 0)
part.Parent = game.Workspace
end
While Loops
While loops are used when you don’t know beforehand how many times the loop should run. They execute as long as the condition evaluates to true.
The Basic Syntax of a While Loop
while condition do
-- code to repeat
end
condition: A logical expression evaluated before each iteration. If it evaluates to false, the loop stops.
The loop body contains code to execute repeatedly. Usually, something in the loop modifies the condition to prevent an infinite loop.
Example
local count = 0
while count < 3 do
print("Hello, World!")
count = count + 1
end
The “count = count + 1” line ensures that the while loop stops after 3 iterations. This is similar to the variable and step count in For Loops.
Output:
Hello, World!
Hello, World!
Hello, World!
Example
local gameRunning = true
while gameRunning do
print("The game is active!")
wait(5) --wait 5 seconds
gameRunning = false -- Condition changes to stop the loop
end
Common Mistake
Infinite loops: make sure the condition will eventually become false, or the loop will run forever, which results in an infinite loop!
Example:
while true do
print("This will run forever!")
end
Looping Tasks
Loops are perfect for:
- Automating repetitive tasks like spawning objects.
- Iterating over lists or arrays (e.g., checking players in a game).
- Animating characters or objects with repeated movements.
For example, if you are creating a countdown in a game:
local countdown = 10
while countdown > 0 do
print("Time left: " .. countdown)
wait(1) --wait 1 second
countdown = countdown - 1
end
print("Go!")
Exercise
Write a loop that spawns 5 balls and makes them fall.
Show/Hide
for i =1, 5 do
local ball = Instance.new(“Part”)
ball.shape = Enum.PartType.Ball
ball.Size = Vector3.new(2,2,2)
ball.Position = Vector3.new(0, i*5, 0)
ball.Anchored = false
ball.Parent = game.Workspace
end
Extension: Animations!
Segment on animations:
local animation = Instance.new(“Animation”)
animation.AnimationId = “rbxassetid://15621353377”
local animationTrack = script.Parent.Humanoid.Animator:LoadAnimation(animation)
animationTrack:Play()
Nested Loops
Nested loops are loops inside of a loop! This is good for more complex tasks that require complex iterations.
This is the basic syntax:
Basic Syntax for Nested Loops
for i=1, outer_limit do
for j=1, inner_limit do
–code to execute
end
end
The outer loop runs first, controlling the number of times the inner loop is executed.
The inner loop completes all its iterations for each iteration of the outer loop.
Example
for x=1, 3 do
for y=1, 3 do
print("Coordinates: (" .. x .. ", " .. y .. ")")
end
end
Output:
Coordinates: (1, 1)
Coordinates: (1, 2)
Coordinates: (1, 3)
Coordinates: (2, 1)
Coordinates: (2, 2)
Coordinates: (2, 3)
Coordinates: (3, 1)
Coordinates: (3, 2)
Coordinates: (3, 3)
Breaks and Continues
Sometimes, you need more control over how a loop executes. Lua provides two key statements: break
and continue
.
break: Exits the loop entirely
for i=1, 10 do
if i == 5 then
break
end
print(i)
end
Output:
1
2
3
4
continue: Skips the current iteration and moves to the next one
for i=1, 10 do
if i%2 == 0 then
continue -- skip even numbers
end
print(i)
end
Output:
1
3
5
7
9
Congratulations—you now know about loops in Lua!