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     ;function arguments, :a and :b, are local variables
  let "s :a + :b  ;also :s is a local variable
  output :s^2
end

print sum2 2 3    ;call to sum2, which creates local variables
;print :s         ;error: :s variable exists only during sum2 execution

Output:

25

Example 2:

to class :a :b
  let "priv :a + :b  ;local variable - "protected"
  make "s2 :priv^2   ;global variable - "public"

  to get_s           ;getter for the protected variable
    op :priv
  end

  to set_s :s        ;setter for the protected variable
    make "priv :s
    make "s2 :s^2    ;can also do any other associated code
  end
end

make "t (newt $class 2 3)
print get_s @ :t
;print :priv @ :t    ;error: variable :priv is not accessible
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