66 lines
1.2 KiB
Markdown
66 lines
1.2 KiB
Markdown
|
# Subroutines
|
||
|
Sometimes in Granite, you will need to be able to call subroutines (a kind of function) instead of jumping and be able to _return_ to where you were before. This is possible!
|
||
|
|
||
|
## New operations
|
||
|
* `:#`, stack push, pushes the current location to the stack, allowing a return
|
||
|
* `:|`, return, returns back to the previous pushed location, crashes if no location pushed
|
||
|
|
||
|
## Tutorial
|
||
|
Look at this program:
|
||
|
|
||
|
```
|
||
|
:?x
|
||
|
:&x,temp
|
||
|
:=default,temp,0
|
||
|
:@print
|
||
|
:^x
|
||
|
:!x
|
||
|
:~
|
||
|
|
||
|
:@default
|
||
|
:>10,x
|
||
|
:<print
|
||
|
```
|
||
|
|
||
|
This program will take a number, add 1 to it and print it out, but default to 10 if a string is passed in.
|
||
|
|
||
|
A more nicer way to do this could be with subroutines!
|
||
|
|
||
|
First, move the default label and its two operations above the prompt and define an entry label above the prompt but below the default label like this:
|
||
|
|
||
|
```
|
||
|
:<entry
|
||
|
|
||
|
:@default
|
||
|
:>10,x
|
||
|
:<print
|
||
|
|
||
|
:@entry
|
||
|
:?x
|
||
|
:&x,temp
|
||
|
:=default,temp,0
|
||
|
:^x
|
||
|
:!x
|
||
|
```
|
||
|
|
||
|
Now before the conditional jump to default after the type check, add a `:#` operation and replace the `:<print` operation with `:|`
|
||
|
|
||
|
The program now functions the same, but looks much more neater with subroutines!
|
||
|
|
||
|
## After example
|
||
|
```
|
||
|
:<entry
|
||
|
|
||
|
:@default
|
||
|
:>10,x
|
||
|
:|
|
||
|
|
||
|
:@entry
|
||
|
:?x
|
||
|
:&x,temp
|
||
|
:#
|
||
|
:=default,temp,0
|
||
|
:^x
|
||
|
:!x
|
||
|
```
|