Oct 7, 2013

vJASS for mules #2: Conditionals

Sometimes you want that a code block only be executed if determined condition be satisfied. That's what conditionals are for. See the example:

integer level = 10
if level > 10 then
    // Do something
endif

That's a example of condition. We use the keyword "if" preceded of the condition you want to test and the keyword "then". On the lines below it's written the code block that only will be executed if the condition that you asserted is true. Lastly, the keyword "endif" determines the end of the conditional block.

Of course that's a condition you already know that it will never be satisfied, but almost never you know the real state of a variable. 

Else blocks
What if, in the condition above, you want that the program run an alternative action in case of the condition don't be satisfied? Well, you can insert an else block. See the example:

if level > 10 then
    // Do something in case of condition was satisfied
else
   // The condition wasn't satisfied
endif

Elseif blocks
But now if you want to test many conditions, for example, for when the level is between 0..10, 10..20, 20..30, etc, you will need an elseif block:

if level < 10 then
    // Do something
elseif level >= 20 and level < 30 then
   // Do another thing
elseif level >= 30 and level < 40 then
   // Do another thing
...
else
   // Nothing was satisfied
endif

Let's try to understand what's happening here. The program tests the first condition, "level < 10". Is it true? If it is, executes the block code of that condition, else, go to the next condition. The next condition is "level >= 20 and level < 30". Is it true? And so on... 
A important note: When the program enters on a block, it reads all of it and jumps of the entire conditional block out. It means that even if there are more true conditions below, it will be ignored.


Answer mentally:

  • What are conditionals? What are their utilities?
  • What are else blocks? When they are used?
  • What are elseif blocks? When they are used?

<<Previous>>                                                                                  <<Next>>

No comments :

Post a Comment