Assignment of variables

First we have a look at variables, then we look at assigning values to those variables.

Variables are words that start with a $, in the editor they are highlighted with purple.

Variables can contain any number, string or boolean (true/false) value. Using the assignment, =, a variable is given its content. It will keep that content until the program finishes executing or until the variable is reassigned to something else.

You can use variables, once assigned, just as if they are their content. For instance in the following piece of TurtleScript:

$x = 10
$x = $x / 3
print $x

First the variable $x is assigned to 10. Then $x is reassigned to itself divided by 3 — this effectively means $x is reassigned to product of 10 / 3. Finally $x is printed. In line two and three you see that $x is used as if it is its contents.

Variables have to be assigned in order to be used. For example:

print $n

Will result in an error message.

Please consider the following piece of TurtleScript:

$a = 2004
$b = 25

# the next command prints "2029"
print $a + $b
backward 30
# the next command prints "2004 plus 25 equals 2029"
print $a + " plus " + $b + " equals " + ($a + $b)

In the first two lines the variables $a and $b are set to 2004 and 25. Then in two print commands with a backward 30 in between are executed. The comments before the print commands explain what they are doing. The command backward 30 is there to make sure every output is on a new line. As you see variables can be used just as if their where what they contain, you can use them with any kind of operators or give them as input when invoking commands.

One more example:

$name = ask "What is your name?"
print "Hi " + $name + "! Good luck while learning the art of programming..."

Pretty straight forward. Again you can see that the variable $name, treated just like a string.

When using variables the inspector is very helpful. It shows you the contents of all variables that are currently in use.