| abstract
| - A conditional operator is a programming construct whose value depends on some designated condition. In NWScript, there is one conditional operator, the ternary ?: operator, which is shorthand for certain types of "if-else" statements. The ?: operator has the format conditional ? value-if-true : value-if-false where the first part is a conditional whose value will be checked (hence the use of the question mark after it). If the conditional evaluates to a true value, the entire expression evaluates to value-if-true; otherwise it evaluates to value-if-false. This compresses some relatively common "if" statements into a single line, which can simplify and clarify some scripts if used wisely. Specifically, assigning the ?: operator to the variable x is equivalent to if ( conditional ) x = value-if-true; else x = value-if-false; While there may be no difference in the efficiency of the resulting script, the single-line version with ?: is often easier for a human to read, making the script easier to maintain. Use of the ?: operator is not limited to assignment. In some cases, it can even be used to eliminate an assignment. For example, the following script snippet if ( GetIsAreaInterior() ) sOverhead = "ceiling"; else sOverhead = "sky"; SpeakString("The " + sOverhead + " is falling!"); can be replaced by the line SpeakString("The " + (GetIsAreaInterior()? "ceiling" : "sky") + " is falling!"); When using the operator in this way (in the middle of a larger expression), it is usually necessary to use parentheses around the conditional operator's part of the expression. (In terms of the order of operations, the conditional operator is evaluated before assignment operators, but after everything else.) Extra care may be warranted for this use, though, as excessive use of the conditional operator can result is a less readable script. Sometimes a well-named variable is more comprehensible than a cryptic use of the conditional operator. Taken a step further, a conditional operator can be used inside another conditional operator (nesting them), similar to how "if-else" statements can be nested into "if-else if-else" statements. Again, care should be taken, as nesting these operators can result in greater confusion, rather than greater clarity. For example, checking if a number is positive, negative, or zero can be done with the following script. string sResult; // Determine if nNumber is positive, negative, or zero. if ( nNumber > 0 ) { sResult = "Positive"; } else if ( nNumber < 0 ) { sResult = "Negative"; } else { sResult = "Zero"; } With the conditional operator, this could be rewritten as a single line. // Determine if nNumber is positive, negative, or zero. string sResult = (nNumber > 0) ? "Positive" : (nNumber < 0) ? "Negative" : "Zero";
|