Set or create local variable
let name value
localmake name value
Stores the value in the local variable with the name, or creates a new local variable, if
there is no variable with the name among local variables created in the current function.
The instruction let
is a shorter synonym used in POOL for the traditional
localmake
.
Example 1:
The example shows how local and global variables are accessed: the global variable :x
with the value 1
is accessible inside the function up to the moment when the local variable with the
same name and the value of 5
is created. Changes made to the value of the local variable do not
affect the global variable.
to fun
print :x
let "x 5
print :x
end
make "x 1
fun
print :x
Output:
1
5
1
Example 2:
This example illustrates how local variables are created and how they can hide variables in the external scope.
Function factorial
is recursive, it calls itself simultaneously decreasing value of the argument,
:x
.
Function argument is always created as a new local variable in a function scope. It hides all variables with
the same name in external functions, including global and shared variables.
Version 1
Expression let "i :i + 1
creates the new local variable for each call to the function factorial
, including nested calls.
To calculate the initial value of the new variable, :i
is used
and its value is taken from the external function before the new variable is created. The external function can
be either factorial
or main function of the #first
turtle.
Value of the variable in the external function remains unchanged.
Version 2
Expression make "i :i + 1
assigns the new value to the variable :i
for each call to the
function factorial
. The new value of :i
is calculated
from its previous value. Value of the variable :i
accessible
in the main function of the #first
turtle is changed.
to factorial :x
let "i :i + 1
print :i
if :x > 1 [op :x * factorial :x - 1]
op 1
end
let "i 0
print factorial 5
print :i
Output (version 1):
1
2
3
4
5
120
0
Output (version 2):
1
2
3
4
5
120
5
See also:
Variables in POOL
make, name - set or create global variable
Table of Content