BSL Control Flow

Code doesn't always run straight from top to bottom. Sometimes you need your script to make decisions or repeat a task multiple times. This is called Control Flow, and BSL handles this using conditional statements and loops.

BSL If...Else

Conditional statements are used to perform different actions based on different conditions. In BSL, you use the standard if, else if, and else keywords.

if: Specifies a block of code to execute if a condition is true.
else if: Specifies a new condition to test if the first condition is false.
else: Specifies a block of code to execute if all previous conditions are false.

// Try it Yourself:
var score = 85;

if (score >= 90) {
    print("Grade: A");
} else if (score >= 80) {
    print("Grade: B");
} else {
    print("Grade: Needs Improvement");
}

Note: BSL supports all standard relational and boolean operators, such as == (equal to), != (not equal), > (greater than), < (less than), && (AND), and || (OR).

BSL While Loop

Loops are handy if you want to run the same code over and over again, each time with a different value.

The while loop executes a block of code as long as a specified condition remains true.

// Try it Yourself:

var count = 0;

while (count < 3) {
    print("While loop count: " + count);
    count = count + 1; // Always remember to update your variable, or the loop will run forever!
}

Output

While loop count: 0
While loop count: 1
While loop count: 2

BSL For Loop

If you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
A for loop in BSL uses the classic C-like syntax: for (initialization; condition; step).

The Iterator Rule (Important!)
Due to how the BSL interpreter handles variable scopes, it has a specific quirk regarding for loops. To avoid "shadowing" behavior (where the loop accidentally creates a new variable that hides an existing one), it is highly recommended to declare your iterator variable outside the for header.

// Try it Yourself:

// 1. Declare the variable outside the loop header
var i; 

// 2. Initialize it, set the condition, and define the step (i++) inside the header
for (i = 0; i < 3; i++) {
    print("For loop iteration: " + i);
}

Output

For loop iteration: 0
For loop iteration: 1
For loop iteration: 2

By declaring var i; before the loop, you ensure the interpreter tracks the variable correctly without unexpected memory quirks.

Now that you can control the flow of your program, the next chapter will show you how to store multiple values in a single variable using BSL Arrays!