Login | Register

The IF statement

August 26, 2006, 09:56 by Calle
[loading]
-->
This is the most useful thing of all things that we have gone through by now, actually, this is what we have wanted to do, but before we could do this we needed the basics. “If” is a English word with synonyms such as stipulation, condition, proviso and qualification. One common use is the argumentation, “if I do this, what will happen then, if he did that what would I do”. That is just what we are about to do:

if (this returns true) {
//do this
}

The tricky part though is to create that “this return true” condition. For this we will need to use the binary operators. Maybe you recognise this from math:

if (10>15) {
//this won’t be executed since 10 is not larger than 15
}

The same thing with variables:

if (nr>another_nr) {
//This might be executed depending on the values of the variables
}

Also you could replace > with < which means “smaller than”, > means “larger than”. Besides you could use == :

If (nr==another_nr) {
//Do this
}

nr = another_nr would work as well, as long as there is if in front of =. It means if nr is equal to another_nr. In other programming languages it wouldn’t work to write = instead of ==, but it does in Game Maker. I recommend you though, to always write == … its easier once you want to learn a new language and definitely more professional if you want to show your code to somebody.
Of course also in the condition entire calculations could be made. If (nr>another_number*2/3+4) would be correct. Sometimes you also want to be able to have more conditions depending on each other nr must be larger than both another_number and another_number2 for an instance. This is highly possible thanks to the Boolean values && and ||. The last one of them means “or”, && means “and”. Exemplified:

If (nr>another_nr) && (nr<another_nr2) {
//this will be executed if nr is larger than another number and smaller than another_nr2
}

&& and || may be replaced by the words “and” and “or”; they are just like the statements. They even get the same bold black mark in the code editor. If (nr>a) and (nr<b) for an example. It is easier to remember, but it doesn’t look as professional.

In your conditions you may also combine == with a other operators. Common combinations are these (where you delete the first = and replace it with another operator):

If (a>=b) || (a<=b) || (a != b)

They mean: If a is larger or equal to b, if a is smaller or equal to b, if a is not equal to b.

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games