CHAPTER 2: LOOPS OF LOGIC



Good job in making it this far; you've just taken your first step into a larger world. Now we're going to be dealing with some things that will make your life much easier in the future.


LESSON 2.1: IF STATEMENTS

Remember how we used comments in section 1 to disable code? Well, sometimes you may need to disable code during runtime using special conditions, or maybe you want code that can run instead of other code. For this, we use an if statement. Take a look at the example:

if(true){
	print("It's true.");
};

if(false) print("This message will self-destruct before you can print it.");

An if statement is written by simply putting if followed by some condition in parentheses. If the condition evaluates to true, then the block of code following the parentheses will be executed. If it's false, the code will be skipped. You can have a single statement after an if, but remember that only the one statement will be controlled; if you want to control more than one statement, then you must put them together in a block.

The condition can be anything; a variable, an equation, even a function.

Now we can look at how if statements can be used as a fork in the road, so to speak, where the condition determines what path the execution will take.

local faveFood = "Cookies";

if(faveFood == "Cookies") print("Om! Nom! Nom!");
else print("You no like cookie?");

When testing a variable as a condition, you must use a logical operator to test its value, otherwise any value other than zero or null will be true, while zero will be false. Logical operators include the following:

== is equal to.
!= is not equal to.
>= is greater than or equal to.
<= is less than or equal to.
> is greater than.
< is less than.

If you want to use more than one condition at once, you would adjoin them using "or" || or "and" && operators. Remember that && has a higher precidence than ||, and will be checked first, much like the order of operations in math. To control this, you can wrap conditions that are meant to be evaluated first in parentheses. Observe:

if(a && b || c) print("If a and b are true, or if c is true.");

if(a && (b || c)) print("If a is true, or if either b or c are true.");

See how parenthases can have such a big impact on conditions? Always keep this in mind when writing them!

Another operator you should be aware of is the not ! operator, which negates whether something is true or false. Take a look at the first if statements we viewed using the not operator.

if(true){
	print("It's true.");
};

if(!true) print("This message will self-destruct before you can print it.");

if(!(true || false)) print("This message will also self-destruct before you can print it.");

Placing the ! between if and its condition list will negate all conditions. Take caution, as this will also affect how && and || will behave! Of course, Squirrel doesn't actually allow this, so if you want to negate all conditions, you will have to bind them together in another parenthesis pair and add ! before that.

EXERCISE 2.1

Write an if/else statement that prints a different message depending on a variable. Have the else statement lead into another if/else pair. Have that lead into another if/else. And another. And a nother.


LESSON 2.2: SWITCH STATEMENTS

Writing those if statements in a daisy chain was pretty exhausting, wasn't it? Sometimes you need to check a statement against multiple possibilities, but don't want to write a whole new if/else for every possible value that statement evaluates to. That's where the switch statement comes in! By using a switch, you can check a condition just like an if, but with as many possible end values as you want. Check this out:

switch(faveFood){
	case "Cookies":
		print("Om! Nom! Nom!");
		break;
	case "Pizza":
		print("Cowabunga!");
		break;
	case "Bananas":
		print("Bananaaaaaaa slamma!");
		break;
	case "Scooby Snacks":
		print("Like, zoinks!");
		break;
	default:
		print("To each their own.");
		break;
};

In a switch, a condition is checked against different cases. When a case is found that matches the switch, the code from there on is executed. If no case matches, and a default exists, it will run the default, otherwise, nothing happens. You'll notice that the code for each case ends with a break statement. Breaks let the system know to leave the current code block. Without a break statement, all code between the successful case and the next one with a break, if any, will be run. Because of this, it is possible to have multiple cases do the same thing, even having them add up in a sort of snowball effect by letting each case have its own code without a break. Here's an example of this:

switch(faveFood){
	case "Cookies":
	case "Pizza":
	case "Bananas":
	case "Scooby Snacks":
		print("Yummy!");
		break;
	case "Cilantro":
		print("Yuck! ");
	case "Garbage":
		print("That's so gross! ");
	case "Worms":
		print("How could you?!");
		break;
	default:
		print("To each their own.");
		break;
};

Setting any of the first four foods as your faveFood will result in Yummy! as the output. The next three, however, will show increasing levels of disgust the further up you go on the list.

EXERCISE 2.2

Stop laughing just because you're on the problem that sounds like "tutu". In this exercise, you'll be doing part of an interrogation system, similar to that found in Morrowind. Write a switch statement with dialog topics to choose from and some information on each topic. Include a case for the NPC to reply when asked about a topic they don't understand, and give them a few things they aren't willing to discuss at all. If you're feeling clever, make some of the cases show different information based on a disposition level.


LESSON 2.3: FOR LOOPS

The for loop is the first method we'll be using to cut down on repetative code. It works a lot like an if statement, by having the name followed by a condition in parentheses and a code block. Unlike an if statement, however, for statements are meant to run their blocks multiple times, but can also be used to not run code at all under the right conditions. However, they can't be coupled with else statements.

for(local i = 0; i < 100; i += 1){
	print((i + 1) + " ");
};

The condition list for a for statement comes in three parts, separated by semicolons. First is the initial statement which is executed before the first iteration. This is usually where a counter variable is declared.

Second is the condition itself used to check if the loop should still run, if at all. This is also checked before the first iteration, as well as every subsequent one. The loop will end when this equates to false.

Lastly, the third statement is executed at the end of each iteration. This is where one would normally increment their counter by whatever amount. It is essential that you make the middle statement equal zero at some point, otherwise your loop will run infinitely, effectively freezing your program.

If you run the code above, you should get a list of numbers from 1 to 100.

Additionally, you can use array.len() to loop through all elements of an array.

local myArray = [1, 2, 3, 4, 5, 6, 7, 8];

for(local i = 0; i < myArray.len(); i += 1){
	print(myArray[i] + " ");
};

One I should bring up now is that when you put something inside something else, such as a loop in another loop, a table/array inside another table/array, or mix and match, this is called nesting. If you're going to use nested loops, be sure to give them their own counter variables!

EXERCISE 2.3

Create a for loop that lists all numbers from 200 to 0, counting by fives. Make sure you count backwards. Separate each value with a space. Remember that you can add strings to numbers.

LESSON 2.4: WHILE LOOPS

While loops are similar to for loops in that they have a condition that is checked every time, but they do not have initialization or increment statements. Look here:

local i = 0;

while(i < 100;){
	print((i + 1) + " ");
	
	i++;
};

While loops have to use pre-existing variables to keep count, and the counter variable must be changed within the loop. The advantage to this is that you can actually decide whether or not to increase the counter based on whatever condition you choose, or even use a different condition entirely. Remember, though, that the condition must eventually become false, otherwise the loop will run until you terminate the process from the task manager.

Another type of while loop is called the do/while loop.

local i = 0;

do{
	print((i + 1) + " ");
} while(i < 100);

This loop does the same thing as a regular while loop, only it is guarenteed to run the code block at least once, even if the while condition is already false.

EXERCISE 2.4

Write a while loop that prints out every number it comes across which is divisible by the number 8 until it has 20 values. Separate each listing with a space. Hint: use the modulo % operator.


LESSON 2.5: FOREACH LOOPS

Normal for loops are great for traversing arrays, but what about tables? Those don't have numbered elements, so how do we run code on each one? Foreach loops are what we use!

local foo = {};

foo.a <- "A";
foo.b <- "B";
foo.c <- "C";
foo.d <- "D";
foo.e <- "E";

foreach(i in foo){
	print(i + "\n");
};

Here, we set it up much like a for statement, but with a few differences. One, the counter variable is not declared using local, and you use a new operator called in to point to the table being used. Foreach loops can also be used on arrays, classes, strings, and any other data type that holds multiple elements.

EXERCISE 2.5

Create a table with different elements and print them out on a new line. Make at least one of them an array, and have it print all elements of that array.


LESSON 2.6: ? OPERATOR

There's actually a shorter way to present an if statement than the one we saw above. Let's take a look at this new notation.

(condition) ? (statement) : (statement);

You may ask yourself, "Why would anyone use this over a standard if?" You may ask yourself "Why am I asking myself if I don't know?" Well, I can't answer the second question, but I can answer the first: because it's useful for short, inline logical checks. For instance, if you wanted to quickly convert a number to its boolean counterpart, you would do this:

(x != 0) ? true : false;

This code will return true if x is any value other than 0. The advantage to this is you can make the answer a single value or variable instead of code, but code is still acceptable.

EXERCISE 2.6

Convert your if statement from exercise 2.1 into a ? statement.


CHAPTER 2 REVIEW

Create an array. Use a while or for loop to push several new numbers onto that array. Create a foreach statement that checks each number to see if it is under 10, between 10 and 20, or above 20. Print each number and the result on a new line.

Next, create a counter variable and set it to zero, and an empty array. Make a for loop that lasts for 5 iterations. In each iteration, it will push a new value to the array. Inside this loop, add another loop for 20 iterations that pushes new elements to each array slot equal to the counter varaible, and increment the counter. Outside the inner loop, add a print() function to print the current row on its own line.


Congratulations! You've learned how to control your program flow using logical operations and looping code. In the next section, we'll be looking at another way of recycling code: the function. You've already called several functions so far, but this time, we'll be learning to make them.

Are you enjoying this tutorial? If so, why not send a donation? You can do so by clicking the donate link at the top of the screen, and if you do, please attach a note to your payment letting me know it's for the tutorial!

<< PREV | NEXT >>