|
  
Delayed Argument Evaluation
Normally, when a function is called, DScript evaluates the
input arguments before entering the function. For example, in the
expression
f(2+3)
DScript first evaluates the expression 2+3 to get 5 and then it evaluates the
expression f(5). Suppose you want
to delay evaluation of the argument and let the function f
decide if and when the expression should be evaluated. For
example, say you want to build a function that behaves like the IF primitive. IF has the format
IF( conditional, trueexpression,
falseexpression )
Depending on the value of conditional, either trueexpression
or falseexpression is evaluated. However, under no
circumstances are both expressions evaluated.
You can get the function's return value right with a
definition like this:
IF(cond,a,b):={
if(cond)
return a;
else
return b;
}
However, the problem with this definition is that all input
arguments are evaluated prior to entering the function IF. Therefore, you will also get
the side effects of evaluating both a and b. For
example,
IF(true,say("True"),say("False"))
will display both True and False.
To cause the evaluation of the input arguments to be delayed,
precede the argument declarations with an ampersand (@) as
follows:
IF(cond,@a,@b):={
if(cond)
return a;
else
return b;
}
Now, pointers to the argument expressions are passed to the
function. This causes the arguments to be evaluated only if they
are evaluated inside the function body.
|