If Expression

The if expression is used to conditionally execute an expression based on the result of a boolean test expression. The syntax for an <if_expr> is one of:

if <expr> then <expr> [else <expr> ]

if <expr> do <expr>

Examples

if a > b do (print d; print e)

a = (if d == 0 then 0 else a / d)

The first <expr> is a test expression that must evaluate to true or false, such as a comparison or logical expression. If the result is true, the then or do <expr> is evaluated and its value is returned as the result of the <if_expr>. If the result is false, the optional else <expr> is evaluated and its value is returned as the result of the <if_expr>. If there is no else or the do form is used, the <if_expr> returns the value undefined.

The do form is provided particularly for use during interactive sessions in the MAXScript Listener. When you enter expressions for immediate evaluation into the Listener, MAXScript determines if your expression is complete and then evaluates it. If you use the optional else form in the Listener and you want to omit the else <expr>, MAXScript continues to "wait and see" if you enter an else <expr>. The line break after the then <expr> is legal and does not cause MAXScript to evaluate the current line right away. As an example, if the following script is entered in Listener, the first line will not evaluate until you enter the second line:

if match x y then print x

print "hello"

When you use the optional else form inside a block or another expression, MAXScript can determine from the code that follows it if you omitted the optional else. Use the do form for if statements without an else as top-level commands in the Listener:

if match x y do print x

As described in Expressions, anywhere you can write an <expr> expression, you can write any construct in MAXScript. In statement-based languages, there is usually one syntax for if statements and a separate one for conditional expressions. In MAXScript, a single syntax is used for both cases. For example, the following two lines of code are both valid, and their meaning should be obvious:

if a > b then print c else print d

x = if a > b then c else d

You can also write the following line, containing a nested if expression and a nested assignment, which is itself an expression:

x = if (if a > b then c else d) < e then f else (g = 23)