Add Making a calculator (unfinished)

2025-09-24 16:55:28 +10:00
parent 0e8887c834
commit 23c4ab3d65

@@ -0,0 +1,62 @@
In this tutorial, we will learn basic string manipulation, control flow and other features of Ground by making a simple calculator program.
Our end goal is to create a program that computes an input, for example `33/5`, `6*3`, `4-10`.
## Getting the input
We will first need to get the input from the user. For this we will use:
```ground
stdout "What would you like to calculate? "
stdin &expression
```
This will store the user's input in the variable `expression`.
## Indexing over a string
We want to go through the string one character at a time, and act accordingly. First, we will create an `idx` (index) variable, and a loop.
```
stdout "What would you like to calculate? "
stdin &expression
set &idx 0
@loop
jump %loop
```
Now, when do we need to exit the loop? Well, if there are n characters in a string, getting the `idx`th character will be out of range when `idx`=n
```
stdout "What would you like to calculate? "
stdin &expression
set &idx 0
getstrsize $expression &length
@loop
equal $idx $length &cond
if $cond %end
jump %loop
@end
```
This will jump to the end when `idx` and `length` are equal, i.e. we have gone through all the characters in the string.
Now, we just need to get the `idx`th character. Luckily this is pretty simple.
```
stdout "What would you like to calculate? "
stdin &expression
set &idx 0
getstrsize $expression &length
@loop
equal $idx $length &cond
if $cond %end
getstrcharat $expression $idx &idxchar
jump %loop
@end
```