1.6 KiB
Type checking
Granite contains two types: integers and strings, and due to how some operations work it may be worth type checking these explicitly within the code.
New operations
:&(variable),(output)
, type check, if(variable)
is an integer then set(output)
to 1 otherwise set(output)
to 0
Tutorial
Look at this simple program:
:?x
:^x
:!x
This program simply asks the user for a number and adds 1 to it.
This program works fine provided the user inputs a number.
? 50
51
But things begin to fall apart if the user does not input an integer.
? I'm an evil string! >:)
Non-number variable x on increment.
Type checking can solve this problem by allowing the programmer to safely recover when an invalid type is detected.
Firstly, we want to make the question a label so make a label called question
above :?x
.
Also add a variable drop after the question
label but before asking the user for x
.
Now directly after :?x
but before :^x
we want to add the type check operation so add :&x,type
after :?x
.
Now we will have an integer corresponding to whether x
is an integer or not. So now after :&x,type
you can add a conditional jump that jumps to the question
label if type
is equal to 0
which means that the user inputted a string.
Now our program is immune to strings messing things up:
? I'm an evil string! >:)
? No strings? :(
? 10
11
Extension
Can you prompt the user to input an integer after incorrectly putting in a string?
After example
:@question
:$x
:?x
:&x,type
:=question,type,0
:^x
:!x