When passing functions into other functions, the normal scoping of variables might be undesired. For example:
k := 10; function r(x) = (x+k); function f(g,x) = ( k := 5; g(x) ); f(r,1)
you probably want the function r
when passed as g
into f
to see k
as 10 rather than 5, so that
the code returns 11 and not 6. However, as written, the function
when executed will see the k
that is
equal to 5. There are two ways to solve this. One would be
to have r
get k
in a
private dictionary using the square bracket notation section
Returning
Functions.
But there is another solution. Since version 1.0.7 there are
true local variables. These are variables that are visible only
from the current context and not from any called functions.
We could define k
as a local variable in the
function f
. To do this add a
local statement as the first statement in the
function (it must always be the first statement in the function).
You can also make any arguments be local variables as well.
That is,
function f(g,x) = ( local g,x,k; k := 5; g(x) );
Then the code will work as expected and prints out 11.
Note that the local statement initializes
all the referenced variables (except for function arguments) to
a null
.
If all variables are to be created as locals you can just pass an
asterisk instead of a list of variables. In this case the variables
will not be initialized until they are actually set.
So the following definition of f
will also work:
function f(g,x) = ( local *; k := 5; g(x) );
It is good practice that all functions that take other functions as arguments use local variables. This way the passed function does not see implementation details and get confused.