# Control Structures

Control structures are statements that manage the flow of Luau code execution. There are four main types of control structures:

• An if then else statement executes code only if a specified condition is true. The code execution doesn't repeat.
• A while loop executes code only if a specified condition is true, and repeats execution while the condition remains true.
• A repeat loop executes code, and repeats execution if the condition is true.
• A for loop executes code a set number of times depending on specified inputs.

The condition for if statements, while loops, and repeat loops can be any Luau expression or value. If a value isn't false or nil, then Luau evaluates it as true in conditional statements. Unlike other scripting languages, Luau considers both zero and the empty string as true.

## If Statements

The basic if statement tests its condition. If the condition is true, then Luau executes the code between then and end.

Ypu can use an elseif statements to test for additional conditions if the if condition is false. You can use an else statement to execute code if all if and elseif conditions fail. The elseif and else parts are both optional, but you can't use either without an initial if statement.

In a chain of if, elseif, and else conditions, Luau tests conditions from top to bottom, stops at the first true condition, and executes the code that follows it.

``````1if 2 + 2 == 5 then
2	print("Two plus two is five") -- Doesn't print because the condition is false
3elseif 2 + 3 == 5 then
4	print("Two plus three is five") -- Doesn't print because the condition is false
5else
6	print("What is two plus two?") -- What is two plus two?
7end
8
9if 2 + 3 == 5 then
10	print("Two plus three is five") -- Two plus three is five
11end
12``````

## While Loops

A whiledo loop evaluates if a specified condition is true or false. If the condition is false or nil, then the loop ends, and Luau skips the code in the loop. If the condition is true, then Luau executes the code in the loop and repeats the process.

``````1local timeRemaining = 10
2
3while timeRemaining > 0 do
4	print("Seconds remaining: " .. timeRemaining)
5	wait(1)
6	timeRemaining = timeRemaining - 1
7end
8
9print("Timer reached zero!")
10--[[ Resulting output:
11Seconds remaining: 10
12Seconds remaining: 9
13Seconds remaining: 8
14Seconds remaining: 7
15Seconds remaining: 6
16Seconds remaining: 5
17Seconds remaining: 4
18Seconds remaining: 3
19Seconds remaining: 2
20Seconds remaining: 1
21Timer reached zero!
22]]
23``````

### Infinite Loops

You can use a whiledo loop to write infinite game loops by setting true as the condition.

``````1while true do
2	print("Looping...")
3	wait(0.5)
4end
5
6--[[ Resulting output:
7Looping...
8Looping...
9Looping...
10Looping...
11...
12]]
13``````

## Repeat Loops

The repeatuntil loop repeats until a condition is true. The conditional test evaluates after the code block runs, so the code block always run at least once. Unlike other languages, the Luau scope of a local variable declared inside a repeatuntil loop includes the condition.

``````1local currentGoblinCount = 18
2
3-- Spawn goblins up to a maximum of 25 in the game
4repeat
5	spawnGoblin()
6	currentGoblinCount = currentGoblinCount + 1
7	print("Current goblin count: " .. currentGoblinCount)
8until currentGoblinCount == 25
9
10print("Goblins repopulated!")
11
12--[[ Resulting output:
13Current goblin count: 19
14Current goblin count: 20
15Current goblin count: 21
16Current goblin count: 22
17Current goblin count: 23
18Current goblin count: 24
19Current goblin count: 25
20Goblins repopulated!
21]]
22``````

## For Loops

A for loop executes code a set number of times, either based on a numerical counter or the number of items in a collection.

### Numeric For Loops

A fordo loop determines the number of times to execute the loop using a counter. The loop is declared with a start value, end value, and optional increment.

Luau sets the counter equal to the start value, executes the code block in the for loop, then adds the increment to the counter. If the increment is positive, then the process repeats until the counter is equal to or greater than the end value. If the increment is negative, then the process repeats until the counter is equal to or less than the end value.

The optional increment defaults to 1. It doesn't need to be a whole number.

``````1for counter = 1, 3 do
2	print(count)
3end
4
5--[[ Resulting output:
61
72
83
9]]
10
11for counter = 1, 6, 2 do
12	print(count)
13end
14
15--[[ Resulting output:
161
173
185
19]]
20
21for counter = 2, 0, -0.5 do
22	print(count)
23end
24
25--[[ Resulting output:
262
271.5
281
290.5
300
31]]
32``````

### Generic For Loops

The generic for loop iterates over items in a collection rather than a sequence of numbers. With generic for loops, you can execute code for each item in the collection, and can easily use each item in the code.

For loops need a function, or iterator, to iterate over different types of collections. The global ipairs() returns an iterator for arrays, and the global pairs() returns an iterator for dictionaries. The string library provides string.gmatch() to iterate over strings.

#### Arrays

The ipairs() function returns an iterator that iterates through numerical indices in a table and returns an index and value for each element. This makes it appropriate for arrays, where all indices are numeric.

``````1local array = {"a", "b", "c", "d", "e"}
2for index, value in ipairs(array) do
3    print(index, value)
4end
5
6--[[ Resulting output:
71 a
82 b
93 c
104 d
115 e
12]]
13``````

#### Dictionaries

The pairs() function returns an iterator that iterates through all indices (including numerical indices) in a table and returns a key and value for each entry in the dictionary. The order of traversing elements in a dictionary table is arbitrary. This makes it appropriate for iterating over dictionaries, where items are stored out of order with non-numeric indices.

``````1local dictionary = {
2	[1] = "a";
3	["Hello"]="b";
4	[5] = "c";
5[true] = "d";
6	["World"] = "f";
7[false] = "e";
8}
9for key, value in pairs(dictionary) do
10    print(key, value)
11end
12
13--[[ Resulting output:
14Hello b
15true d
16false e
17World f
185 c
191 a
20]]
21``````

### Breaking Loops

To force a loop to end, use the break command. The following code sample shows how to break an infinite whiledo loop.

``````1local secondsElapsed = 0
2local timeout = 5
3
4while true do
5	print("Seconds elapsed:", secondsElapsed)
6	wait(1)
7	secondsElapsed = secondsElapsed + 1
8
9	if secondsElapsed == timeout then
10		break
11	end
12end
13
14print("Five seconds elapsed. Time to move on!")
15
16--[[ Resulting output:
170
182
193
204
215
22Five seconds elapsed. Time to move on!
23]]
24``````