Programmer Guide/Command Reference/COND: Difference between revisions
From STX Wiki
Jump to navigationJump to search
No edit summary |
|||
| Line 17: | Line 17: | ||
=== Examples === | === Examples === | ||
#min := cond $#a < $#b ? $#a : $#b | #min := cond $#a < $#b ? $#a : $#b // calculate minimum of #a and #b | ||
#abs := cond $#a < 0 ? num -$#a : $#a | #abs := cond $#a < 0 ? num -$#a : $#a // calculate absolute value of #a | ||
#abs := cond $#a < 0 ? eval $#a*(-1) : $#a // an alternative to the above | #abs := cond $#a < 0 ? eval $#a*(-1) : $#a // an alternative to the above | ||
#absdiff := cond $#a > $#b ? eval $#a-$#b : eval $#b-$#a // absolute difference | #absdiff := cond $#a > $#b ? eval $#a-$#b : eval $#b-$#a // absolute difference | ||
Revision as of 16:29, 14 March 2011
The COND command performs a conditional assignment.
Generally, the conditional assignment takes the following form:
target := COND condition ? expr1 : expr2
target- is a normal assignment target, usually the name of an S_TOOLS-STx variable, e.g.
#var. condition- is a conditional expression like used with the
IFstatement and the miscellaneous loop commands, e.g. the string$#a == 7 || $#a == 42(for more examples, see theIFstatement). - Note that with conditional S_TOOLS-STx expressions there must always be intervening whitespaces between operators and their arguments (unless the argument is quoted). So, both
$#a == 7and'$#a'=='7'are valid expression, whereas$#a==7is not. expr1andexpr2- Both
expr1andexpr2may be any expressions that may be normally used in an S_TOOLS-STx:=assignment, with the only exception of aCONDexpression (meaning that conditional assignments must not be nested for the time being). If, at runtime, the conditional expressionconditionevaluates to truth, the value determined by the first expression,expr1, will be assigned totarget. Ifconditionevaluates to falsehood, it will be the second expression,expr2, that gets assigned to target.
You may use any S_TOOLS-STx conditional expression you like for condition. Equally, there is no restriction on expr1 and expr2, except that they must not be built up from COND expressions themselves. It is even (and also) possible to use command substitutions ($(...)), nesting them as deeply as one feels inclined to.
Notes
- The
CONDcommand is processed by the loader, and is therefore not available in the command line interface. - The
CONDcommand may not contain a nestedCONDcommand.
Examples
#min := cond $#a < $#b ? $#a : $#b // calculate minimum of #a and #b #abs := cond $#a < 0 ? num -$#a : $#a // calculate absolute value of #a #abs := cond $#a < 0 ? eval $#a*(-1) : $#a // an alternative to the above #absdiff := cond $#a > $#b ? eval $#a-$#b : eval $#b-$#a // absolute difference #len := cond $(length $#a) > 0 ? length $#a : length $#b // length of #a or, if empty, of #b
See the file conditional_assignment.sts for further working examples.