Local variables
Local variables are accessible from the function that created them and all nested functions (note: all code out
of any function is actually a body of the #first
turtle's main
function).
Lifetime of local variables is limited to the function execution. On each call to the function a new set of
local variables is created.
In case of a function used as a class definition, local variables become equivalent to the protected
variables known from other programming languages. Such variables are not accessible to @
operator, however they are available in derived classes.
Use local variables wherever it is sufficient. They are most efficient in terms of code speed, they do not
allocate memory when not used, and very important: they allow to keep minimum required access rights, which is
a very good style in the object-oriented programming.
Example 1:
to sum2 :a :b
let "s :a + :b
output :s^2
end
print sum2 2 3
Output:
25
Example 2:
to class :a :b
let "priv :a + :b
make "s2 :priv^2
to get_s
op :priv
end
to set_s :s
make "priv :s
make "s2 :s^2
end
end
make "t (newt $class 2 3)
print get_s @ :t
print :s2 @ :t
(set_s 6) @ :t
print get_s @ :t
print :s2 @ :t
Output:
5
25
6
36
See also:
Data types
Variables, data access
Table of Content