GENERATE/PREV.gifGENERATE/NEXT.gif

For Loop

A for-loop lets you iterate through a range of numbers, time values, or a sequenced collection of values, such as an array or object set.

Examples:

for i = 1 to 10 do print I      -- sequence numbers

for item in table1 do x = x + item.height      -- sequence an array

for t in 0f to 100f by 5f do ...      -- sequence time (given as      -- frames, here)
bigones = for obj in $box*      -- you can sequence pathnames!

where obj.height > 100 collect obj      -- collect the big boxes into      -- an array

The syntax for the for loop is:

for <name> ( in | = ) <sequence> ( do | collect ) <expr>

where <name> is the name of the automatically-created local variable inside the loop <expr> that holds the loop value, and <sequence> is the source of values for the loop which can be one of:

<expr> to <expr> [ by <expr> ] [ where <expr> ]

<expr> [ where <expr> ]

The first <sequence> form is the classic number loop, the first <expr> is the start value, to <expr> is the limit value and the optional by value is the loop value increment. The allowable types are integer, float and time. If the by value isn't given it defaults to 1.

The second form of <sequence> takes a sequencable collection, such as an array or object set, and iterates through all its values, assigning successive elements in the collection to the loop value each time around the loop. MAXScript contains several types of sequence collections, including pathnames, the current selection set, the children of a node, and the stack of modifiers on an object. They are all defined in the MAXScript Class Hierarchy topic.

Each <sequence> source form takes an optional where <expr> which must evaluate to true or false. The where expression is evaluated at the beginning of each loop and only executes the loop body for that loop if the where expression is true.

The do <expr> form simply evaluates the body expression once for each value in the source. 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.

The collect <expr> form gathers all body expression values from each loop iteration and stores them in an array value, which is yielded as the value of the overall for-loop. This is a good way of gathering procedural selections of objects from a scene, for example.