Sunday, April 7, 2013

Intro to GML Part 2: The if Statement

Now that you've learned a bit about what variables are, let's use them to do stuff.  Probably the most basic statement you will run across in GML (and most other programming languages) is the if statement.  It helps control the flow execution in your code.

Here it is in the most basic form:

if (condition){
   //Do Stuff

That might look scary if you haven't done much work in code, but the idea is really simple.  Whenever your script gets to this part, it evaluates the "condition."  It can be any number of things, but usually it's a comparison between two values. If the condition is true, it does the stuff.

Now, let's use it together with some variables, shall we?  Let's make a variable called condition, and set it to one.

condition = 1;

Ok, now make another variable, and set it to 2:

anotherVariable = 2;

We can use the if statement to compare these two things, like this:

if (condition == anotherVariable){
      //Do Stuff

So, do you think we will reach the "Do Stuff" part?  Nope, not in this case.  The if statement asks, "is condition equal to anotherVariable"?  The answer is no, of course 1 isn't equal to 2, so the stuff inside gets skipped over.

Basically, it works like this:

if (true){
   //Do stuff

if (false){
   //Don't do stuff

The if statement has a wide range of uses, so it's pretty important to know.  In future posts, I'll show you how to put it to work in your games.

No comments:

Post a Comment