Subroutines
Similar to loops, subroutines allow the same lines of code to be reused and run again. Unlike a loop, which causes the lines of code to be re-run immediately, a subroutine is like a placeholder that will allow the code to be re-run when the place is returned to by "calling" the subroutine.
Declaring Subroutines
Subroutines are declared using the SUB keyword followed by a name for the subroutine. Then the subroutine's code follows, and finally the subroutine is ended with the END. This is the same keyword as is used to end loops and if-statements. The following code declares a subroutine for drawing a square:
SUB square
REPEAT 4
FORWARD 50
RIGHT 90
END
END
We now have a reusable chunk of code that draws a square. Anywhere in our program that we want to draw a square, we can do so without having to rewrite the code for drawing a square.
Naming Subroutines
Subroutines have the same naming restrictions as variables. Subroutiness can be named using any combination of the letters in the latin alphabet(a-z) and numbers. No "special" characters are allowed in a subroutine name, such as underscores and non-latin characters. No spaces are allowed in a subroutine name. A subroutine name must start with a letter.
Calling Subroutines
After being declared, a subroutine can be called using the CALL keyword followed by the name of the subroutine to call. In the following example, we call a subroutine multiple times to draw multiple squares with 10 units of space between them:
REPEAT 4
CALL square
FORWARD 60
END