Intro to Mel Script Part 8 :: Automatically Repeat a Task Several Times using a "for loop"

Repeating a task over and over is something that we do all the time by hand in Maya. It is much more convenient to let Mel Script to do all of that for you.

We can accomplish this easily by taking advantages of the power of "for loops"

Here are 3 styles of a Mel Script for loop:

////////
// for loop style...
// ...counting by one (very commonly used)
int $i;
for( $i = 0; $i < 5; $i++ )
{
    polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 4 -ch 1-name "cubeA#";       
}

///////
// for loop style...
// ...counting by 2's
int $j;
for( $j = 0; $j < 10; $j = $j + 2 )
{
    polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 4 -ch 1 -name "cubeB#";       
}

///////
// for loop style...
// ...loop through every item in an array of items
string $array[] = {"cubeC1","cubeC2","cubeC3","cubeC4","cubeC5"};
string $each;
for( $each in $array )
{
   polyCube -w 1 -h 1 -d 1 -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 4 -ch 1 -name $each; 
}


All of this typed out inside the Script Editor looks like this:


You can see that each for loop creates 5 cubes.
Each for loop has a different way of counting.



A really important part to look at in a regular for loop is the stuff inside the parenthesis.
It is divided into 3 parts <start >; <end> ;<count by #>
Each section is separated by semicolons.




Here are further descriptions of the three sections:
The first section...




...second section....


...third section.


It is important to note here that $i gets "saved over" each time the loop runs. So, this means that on the first time through the loop $i will equal 0. The second time through $i will equal 1, then 2, then 3, and so on. The moment $i is no longer "less than 5", the loop will cancel itself. This is how we start and end our for loop. In other words, the second section has to return true for the loop to keep on cycling through.

Here is an example of what value $i has each time:


The value that $i has gets printed out in the History Section each time using the "print" Mel Command.
The "\n" in the print statement is another way of saying, "insert a new line". 




























No comments:

Post a Comment