In this section, we will be discussing about loops. What are loops? Loops are code blocks that can store a block of code and repeat that block of code. In Roblox, we got for loops, while loop, and repeat loop. for loops can be used to countdown and loop through a table, a while loop can be used to repeat a block of code with a condition, and the repeat loop can be used to repeat a block of code until a condition is met. In a loop, we got "continue" and "break". Break is used to stop a current running loop and continue the code blocks that are below the loop and continueisused to move to the next iteration.
WHILE LOOP USAGE
local myBool = true
while myBool then -- If myBool is true then the loop is running
-- We insert a task.wait() to wait 1 second here so it doesn't crash the script and studio.
task.wait(1) -- Wait for 1 second before run the loop again.
print('The loop is running')
end
FOR LOOPS USAGE
for i = 10, 0, -1 do
task.wait(1) -- Wait for 1 second before run the loop again.
print(i, ' seconds has passed') -- Will print "x seconds has passed"
end
Loop through a table
local myTable = {
myString = 'Hello';
myBool = false;
myNumber = 1;
}
for i, v in pairs(myTable) do -- Pairs return both key and value!
print(i, v) -- This will print "myString & Hello, myBool & false, and myNumber & 1"
end
Or:
local myTable = {
'Hello';
false;
1;
}
for i, v in ipairs(myTable) do -- ipairs return only value and key by number instead of it name!
print(i, v) -- This will print "1 & Hello, 2 & false, and 3 & 1"
end
REPEAT LOOP USAGE
local myBool = false
local secondsHasPassed = 0
repeat task.wait(1) -- Wait for 1 second before running the loop again.
secondHasPassed += 1
print('Repeat loop is running')
if secondsHasPassed >= 5 then -- After 5 seconds set myBool to true to stop the code.
myBool = true
secondsHasPassed = 0
end
until myBool -- Repeat the loop until the boolean is true
print('Repeat loop has stopped')
BREAK USAGE
local timeHasPassed = 0
while task.wait(1) do
timeHasPassed += 1 -- Add 1 every second to the variable
if timeHasPassed >= 3 then -- Break loop after 3 seconds passed.
print('Three seconds has passed')
break -- Break the loop to stop it using break
end
end
print('Hello, World!!') -- This will print "Hello, World!!"
CONTINUE USAGE
for i = 1, 12, 1 do
if i % 2 ~= 0 then -- Check if number is divisible by 2. If not then skip to next iteration.
continue
end
print(i, ' is an even number') -- This will output 2, 4, 6, 8...
end