Master conditional statements and loops to control the flow of your scripts.
If statements allow you to execute code only when certain conditions are met.
local health = 50
if health < 100 then
print("Health is low!")
end
The code inside the if block only runs when the condition is true.
local score = 85
if score >= 90 then
print("Grade: A")
elseif score >= 80 then
print("Grade: B")
elseif score >= 70 then
print("Grade: C")
else
print("Grade: F")
end
Use elseif for multiple conditions and else for a default case.
For loops repeat code a specific number of times.
-- Count from 1 to 10
for i = 1, 10 do
print("Number: " .. i)
end
-- Count with step
for i = 0, 100, 10 do
print(i) -- 0, 10, 20, 30...
end
Format: for variable = start, end, step. Step is optional (default is 1).
local players = {"Alice", "Bob", "Charlie"}
for index, name in ipairs(players) do
print(index .. ": " .. name)
end
Use ipairs() to iterate through array-like tables with indices.
While loops repeat code as long as a condition is true.
local count = 1
while count <= 5 do
print("Count: " .. count)
count = count + 1
end
Be careful to update the condition variable, or you'll create an infinite loop!
local num = 1
repeat
print(num)
num = num + 1
until num > 5
Similar to while, but checks condition AFTER each iteration (runs at least once).
Create an if statement that checks health and prints different messages.
local health = 45
-- Write your if statement here
local health = 45
if health > 75 then
print("Health is good!")
elseif health > 25 then
print("Health is okay")
else
print("Critical health!")
end
Use a for loop to create a countdown from 10 to 1.
-- Create a countdown loop
print("Liftoff!")
for i = 10, 1, -1 do
print(i)
wait(1) -- Wait 1 second between counts
end
print("Liftoff!")
Continue your learning journey