Control Flow Statements Continued



Loop / Iteration statement:
A Loop statement is a method of executing a block of code repeatedly until an exit condition is met. Loops allow us to be efficient in our coding by using less instruction to repeat running a process on multiple objects. For example, instead of writing the following pseudo code:

Open fileOne
Export fileOne
Close fileOne
Open fileTwo
Export fileTwo
Close fileTwo
...
Open lastFile
Export lastFile
Close lastFile


With loop statement, we can write a more efficient code as follow:
for every file in my directory do open, export and close file


Also, loop statement gives us the ability to easily run repeated operation on data with unknown size. For example, we could read and process each line in a file until we reach the end of the file without any previous knowledge of how many lines it has by writting the following pseudo code:


while end of file wasn't reached, read and process a line from myFile

Loops can be categorized under the following three types with varying syntax within each programming languages:


All loops are constructed with the following section:



MEL, for loop

//It is best to use a "for loop", If you know how many time you need to repeat a process. Only integers can be reliably used in a count-controlled loop.
int $n;
for($n=0; $n<100; $n++)
{
   //int n = 0 is initializing the count, n < 100 //is the terminating condition
   // and n++ (n = n + 1) is the iteration condition
   print (n + "\n"); // the body of the loop
}



MEL, for-in (for each)

//The "for-in loop" is best used for iteration over a list of objects

string $list[] = `ls -sl`;
string $item;
for($item in $list)
{
    print ($item + "\n");
}



MEL, while

/*The "while loop" is best used to process an unknown number of objects and terminate the operation when a condition is false. "While loop" checks the truthfulness of the initial condition at the start of each iterations to continue executing the code body. If the conditions never evaluate to a false the script goes into an infinite loop and there is no way you can interrupt it. You have to restart the Maya application.*/
string $list[] = `ls –sl`;
int $index = 0;
while($index < size($list))
{
    print ($list[$index] + "\n");
    // if you forget to increment $index, you'll have an infinite loop*
    // and the only way to stop it is to exit Maya
    $index++;
}



MEL, do-while

//In a do while we post-test the condition, which means the code will run at least once even though the condition was not met.
do
{
    print ($list[$index] + "\n");
    $index++;
} while($index < size($list))







Maxscript:

Maxscript, for loop

/*
The standard "numbered loop" has a start value, a "to" value as a limiting factor and an optional "by" as an incrementing value. The allowable value types are integer, float and time. If the "by" value isn't given it defaults to 1.
*/

for i = 0 to 100 by 2 do
(
    print i
)


--below is a time sequence given as frames
for t in 0f to 100f by 5f do
(
    sliderTime=t
)



Maxscript, additional for variations

– The for-in takes a collection, such as an array and iterates through all its values

var myMap
for MyMap in aTextureMaps do
(
    if (matchPattern MyMap.name pattern:".dds") then
    (
        print "myMap is a dds type\n"
    )
)


/*
If an optional while test is specified, the for loop will terminate if the test evaluates to false. The while test expression must evaluate to a boolean (true/false).
*/

Local notFound = true


for i = 1 to 10 while notFound do
(
    if i== 5 do
    (
        notFound = false
        format "found 5\n"
    )
    format "%\n" i
)


/*
The optional "where" expression is evaluated at the beginning of the iteration and only executes the loop body if it evaluate to true. The "do" expression simply evaluates the body expression once for each value in the sequence. The collect phrase gathers and stores the expression values from the loop in an array, which is then returned as the overall for loop.
*/

bigones = for obj in $box where obj.height > 100 collect obj – collect the big boxes into an array
– you can sequence pathnames!


– The loop variable is visible to the code in the body expression as though it was declared locally and initialized to the successive loop values each time. Once the for loop exits, the "for loop" index variable is no longer accessible.



Maxscript, while loop

– In while statement, we pre-test "t" value before we start running the code inside the while statement and re-test "t" value on every iteration.

t = 10;


while t > 0 do
(
    format "t minus % seconds and counting.\n" t
    t = t - 1
)



Maxscript, do-while

/*
In a do while we post-test the condition, which means the code will run at least once even though the condition was not met. Usually, do-while is used in UI menu selection since it has to show up first for the user select to continue or not.
*/

do (
    format "You see me only when random is not 0.\n"
) while (random 0 1) != 0





Python:


Python, for loop

#The range function creates a list containing numbers defined by the input.

for x in range(0,3):
    print 'We are on time %d'% (x)


#The xrange function creates a number generator. You will often see that xrange is used much more frequently than range.
for x in xrange(1,11): #start from 1 to 11
    print '%d * %d = %d' % (x,x,x*x)



Python, for-in loop

Strings and Lists as an iterable

mystring ="Hello World"

for c in mystring:
    print c #prints one character at a time


collection = ['Maya','d', 100]
for x in collection:
    print x


A python dictionary is an extremely useful data storage construct for storing and retreiving key:value pairs

my_dict = {
    'apple': 'red',
    'orange': 'orange',
    'banana': 'yellow'
    }
for key, value in my_dict.iteritems():
    print key, value



Python, while loop

count = 0

while (count < 9):
    print 'The count is:', count
    count = count + 1


#The break statement in Python terminates the current loop and resumes execution at the next statement. The continue statement in Python rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

var = 10 # initial count
while var > 0:
    print 'Current variable value :', var
    var = var -1
    if var == 6:
        continue #below skipped when var is 6
    if var == 5:
        break #loop will terminate when var is 5




lua:

Lua,for loop

--The "for statement" has two forms: one numeric and one generic.
--The numeric for loop repeats a block of code while a control variable runs through an arithmetic progression. You can use break to exit a for loop.
--All three control expressions are evaluated only once, before the loop starts. They must all result in numbers. var, limit, and step are invisible variables.
for v = 0, 10, 2 do --0 is initial value, 10 is end value, 2 is incrementing steps
    if v == 6 then
        print "reached 6 and exiting"
        break
    end
    print ( v )
end

--The generic "for statement" works over functions, called iterators. The iterator function is called to produce a new value, stopping when this new value is nil. The generic for loop has the following syntax:

#!/usr/bin/lua
local mytable = {"one", "two", "three"}
mytable[4] = "four"
mytable[6] = "six" --notice the gap at 5
mytable["name"] = "Steve" --notice this is a string, not an integer
mytable[1.5] = "one-point-five" --notice this is a float, not integer


for k, v in ipairs(mytable) do
    print(string.format("k=%s, v=%s",tostring(k),tostring(v)))
end
http://www.troubleshooters.com/codecorn/lua/lualoop.htm




Lua, while loop

The Lua while loop acts pretty much like while loops in all languages, it tests on top, and you can change all and any variables within it because the test gets re-tested on every iteration.

n = 1
while n <= 15 do
print (n)
n = n + 1
end



Lua, repeat loop

--In the repeat–until loop, the inner block does not end at the until keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block

k = 1
repeat
print (k)
k = k + 1
until k > 5