Mel - Maya Embedded Language

<HOME>   <PREVIOUS>   <NEXT>

Loops and If Blocks - for loop

if then else
for
for in
while
do while
switch

for

The for loop is mainly used to repeat something a number of times.
A for loop mainly consists of:

for(initial execution; test condition; increment)
{
do something;
}


string $myArray [ ] = {"one","two","three","four"};
int $myArraySize = size($myArray);
for ($i =0; $i<$myArraySize; $i++)
{
      if ($myArray[$i] == "one")
          print ("\n"+$myArray[$i] + " dead roach!");
     else
          print ("\n"+$myArray[$i] + " dead roaches!");
}

returns:

one dead roach!
two dead roaches!
three dead roaches!
four dead roaches!

When you want to find the size of a given array, use size(arrayname);. This comes in handy in situations when we want a loop to happen based on the size of the array.

Exercise:Create 6 spheres using a for loop.
Each sphere should have a different radius and be moved on the x axis to a new place on the stage inside the loop using the loop variable.

Exercise:Change the loop so it makes spheres with random sizes and they are moved to random x, y, and z positions. (Use the loop variable and some arithmetic operators).