Mel - Maya Embedded Language

<HOME>   <PREVIOUS>   <NEXT>

Loops and If Blocks

if then else
for
for in
while
do while
switch

If Blocks (if then else)

If blocks are used to compare values and perform an action based on the given results.

if (value comparison-operator value)
{
      do something
}

It could be written as:

if (comparison of two values)
do operation;

Note: if you have one operation after the comparison then you do not need the curly brackets {}. But it is good practice to always use them.

Example of an if block:

int $a = 15;
int $b = 6;
int $c = 0;

if ($a > $b)
{
      $c = $a - $b;
}

print $c;
The if statement checks to see if $a is larger than $b. If the comparison is true, we change the value of $c.

Example of an if block using else:

int $a = 15;
int $b = 6;
int $c = 0;

if ($a > $b)
{
      $c = $a - $b;
}
else
{
      $c = $a * $b;
}

print $c;
The else enables you to do do two different actions - one if it is true and another if it is false.

Exercise: Create an array of four object names.
Create another variable to hold the name of the object you are looking for.
Write an if block that checks to see if the third element in the array is the correct one.
If so, create an object using that as the name.
If not, create an object using the first element in the array as the name.

<Top>