> For the complete documentation index, see [llms.txt](https://docs.sacruda.nl/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sacruda.nl/sacruda-basic/programmer-guide.md).

# Programmer guide

The Sacruda flavour of BASIC is a love letter to the simple yet powerful programming language from the 80s, used by millions. I took the concept of BASIC and applied my own spin to it to create what I believe to be a very useful addition to Sacruda. It's different and new, while still keeping the low barrier to entry that made all of those BASIC flavours from back in the day so intuitive and enjoyable to use.

## Table of contents

* [1. Getting Started](#1-getting-started)
  * [1.1. Running BASIC code](#11-running-basic-code)
  * [1.2. Writing your first BASIC program](#12-running-your-first-basic-program)
* [2. The basics of BASIC](#2-the-basics-of-basic)
  * [2.1. Talking and listening](#21-talking-and-listening)
  * [2.2. If this, then that](#22-if-this-then-that)
    * [2.2.1. The kinds of expressions](#221-the-kinds-of-expressions)
  * [2.3. While this, do that](#23-while-this-do-that)
  * [2.4. Variables](#24-variables)
  * [2.5. Playing a Sacruda sound](#id-2.5.-playing-a-sacruda-sound)
  * [2.6. Errors](#26-errors)
  * [2.7. STOP!](#27-stop)
* [3. Advanced BASIC](#3-advanced-basic)
  * [3.1. Environment variables](#31-environment-variables)
  * [3.2. Mathematics](#32-mathematics)
    * [a. Random number generator](#a-random-number-generator)
    * [b. Plugging variables in](#b-plugging-variables-in)
    * [c. Binary!](#c-binary)

## 1. Getting started

To write code for Sacruda BASIC, you really only need a .bas file and one of our text editors. I usually use Cod, but browser support varies and I know that it has a bunch of bugs. Either way, create a new `.bas` file somewhere and open it in your text editor. I almost always put my basic files in a folder on the Desktop so that I can easily navigate there in the Terminal. Oh right, the Terminal.

### 1.1. Running BASIC code

To run a BASIC file, you'll want to use the Sacruda Terminal. Open a new Terminal instance, navigate to the folder in which your BASIC file is located, then type `basic <filename>` to run it. There's also several flags you can give the `basic` command to change how it behaves:

* `--slowdown <ms>` specifies the amount of milliseconds BASIC waits after every line of BASIC code (default is 20)
* `--debug` is used to view the verbose output of the interpreter if it does something unexpected that isn't listed in this documentation. You can pair this with `--slowdown` to read the debug output without being able to read as fast as the Flash.

### 1.2. Writing your first BASIC program

Let's start with the defacto standard for learning a new programming language; hello world. In your BASIC file, enter the following code:

```
print "hello, world!"
```

When you run the file using the method described in §1.1, you should see the following in your terminal:

```
user: U:/Home/Desktop $ basic hello.bas

hello, world!
user: U:/Home/Desktop $ 
```

And just like that, you've written your very first lines of BASIC code. Congratulations! Now, let's kick it up a notch.

## 2. The basics of BASIC

Now we're going to cover several of the basic principes of Sacruda BASIC. Note that the language is growing; every new version of Sacruda adds new functionality, so these sections may change when a new version releases.

### 2.1. Talking and listening

We've already looked at how you can talk to the user using the `PRINT` keyword. But instead of having a one-sided conversation, maybe we should ask the user something. This can be done using the `INPUT()` *function* (NOT a keyword!). Functions are built-in utilities you can call to get some value back. We can use the `INPUT` function to ask the user something, and store what they answered in a *variable*:

```
var name = input("What is your name? ")

print "Hello, $name!\n"
```

Running this code will result in the following:

```
user: U:/Home/Desktop $ basic hello.bas


What is your name? John Smith
Hello, John Smith!

user: U:/Home/Desktop $ 
```

With this code, we've created a *variable* called "name" and put what the user entered into it. Then, we echoed that value in the `print` keyword by putting a dollarsign in front of the variable name. Don't worry about that for now, §2.4 talks more about variables.

### 2.2. If this, then that

With the `IF` keyword, you can have the program run some code if a *condition* is met. For example, let's check if the user actually entered their name:

```
var name = input("What is your name? ")

if $name eq "" then
  print "You didn't enter your name :(\n"
  gostart
endif

print "Hello, $name!\n"
```

In the above code, we're asking the user for their name, after which we check if the name is equal to (`eq`) an empty string. If it is, we use the `GOSTART` keyword to go back to the start of the program, which in this case once again asks the user for their name. Running the code gives us the following result:

```
user: U:/Home/Desktop $ basic hello.bas

What is your name? 
You didn't enter your name :(

What is your name? John Smith
Hello, John Smith!

user: U:/Home/Desktop $ 
```

You can use the `NOT` modifier to *invert* the condition of an `IF` keyword. For example:

```
if not "hello" eq "world" then
  print "Hello!"
endif
```

In this example, `Hello!` will be echoed because the condition was inverted.

#### 2.2.1. The kinds of conditions

There are several types of conditions that you can use in keywords like `WHILE` and `IF`. Here's a list of them:

* `<A> EQ <B>` - Is A equal to B
* `<A> NEQ <B>` - Is A **n**ot **eq**ual to B
* `<A> GT <B>` - Is A **g**reater **t**han B
* `<A> LT <B>` - Is A **l**ess **t**han B
* `<A> GTE <B>` - Is A **g**reater **t**han or **e**qual to B
* `<A> LTE <B>` - Is A **l**ess **t**han or **e**qual to B

If you use a condition-type that BASIC doesn't recognize, the program will stop with an error message.

## 2.3. While this, do that

The `WHILE` keyword is very similar to `IF`, in that it also uses expressions (§2.2.1). However, it is different in that the `WHILE` keyword will keep executing what's inside it until the condition is met. That does mean that the `WHILE` keyword will loop infinitely if the condition is never met. Let's write a new program:

```
var start = 0
var end = 10

while $start neq $end do
  print "start = $start\n"
  var start = math($start + 1)
endwhile

print "\nThe loop ended!\n"
```

In this program, we're comparing the variable 'start' to 'end'. As long as 'start' is not equal to 'end' (`neq`), we're printing the value of 'start', and then using the `MATH()` function to increase 'start' by one. Finally, when the loop has ended, we tell the user that the loop ended.

Running this code gives the following result:

```
user: U:/Home/Desktop $ basic hello.bas

start = 0
start = 1
start = 2
start = 3
start = 4
start = 5
start = 6
start = 7
start = 8
start = 9

The loop ended!

user: U:/Home/Desktop $ 
```

A `STOP` statement *can* be used to break out of a WHILE loop and end the program.

## 2.4. Variables

A *variable* stores something like a number or a string. You can use variables to keep track of stuff while your application is running. Take the example of §2.1. In this section, we're putting a value into a variable named 'name'. We're then using the `PRINT` keyword to echo the *value* of that variable to the user.

To *set* a variable, you can use the `VAR` keyword. If a variable with the specified name doesn't exist, a variable will be created. If it does already exist, its value will be replaced with the new value. Let's take a look at the following example:

```
var a = 25
print "You have $a apples."
```

In the above example we're putting the value `25` into the variable 'a'. We can then read back the contents of that variable by putting a dollarsign (`$`) in front of it. If you're trying to read a variable that doesn't exist, the program will exit with an error; `No such variable <name>`. A variable name can be up to 6 characters long. Once again, if you try to set a variable that already exists, the old value will be replaced with the new value:

```
var a = 25
var a = 200
print "You have $a apples."
```

In this example, the output will be `You have 200 apples.` because we're setting the same variable to a new value. Variables can do a lot more than just simple values though, you can also store JSON objects and arrays in them. §3 talks more about those advanced concepts.

The `VAR` keyword does its best to parse whatever you put into it into a native type. For example, the string `"false"` will become a boolean, the string `"[1,2,3]"` will become an array, `"{}"` will become a JSON object, etcetera. If the value can't be parsed to its native variant, it's kept as a string. `"asdf"` can't be turned into a number, so its type will stay `string`.

## 2.5. Playing a Sacruda sound

With the `SOUNDBUS` keyword, you can play an Sacruda sound from the SoundBus kernel module. To view which sounds you can play, open the Terminal and type `soundbus list` as a command.

For example, to play the "Information" dialog sound, use the following code:

```
soundbus "arcos.dialog.info"
```

As of right now, the `SOUNDBUS` keyword can only *play* sounds: you can't use it to load sounds into the Kernel module or modify existing sounds. That may come in the future.

## 2.6. Errors

Errors in Sacruda BASIC tell you when something isn't working right. This may be an issue with Sacruda, or just with your code. For example, if you made a typo, you might get one of these:

```
Error in test.bas:4:6 - Unknown expression 'nqe'

   ║  
 4 ║  if $a nqe $b then
   ║        │
   ║        └─ Unknown expression 'nqe' (4:6)

  at if block (line 4)
  at engine [EXECUTE] (line 1)
```

In this case, the BASIC engine is telling you that the expression type "nqe" isn't valid. Instead, you probably meant to enter "neq" for "not equal".

You can also throw an error message yourself, which will be echoed to the console, after which the program is stopped. Consider the following code:

```
var num = input("Enter a number: ")

if typeof($num) neq "number" then
  error "You didn't specify a valid number!"
endif

var double = math($num * 2)
print "$num x 2 = $double"
```

This code works because the `VAR` keyword does its best to parse whatever you put into it into a native type. For more information, see §2.4.

In this program, entering an invalid number will cause the program to error:

```
Enter a number: asda

Error in test.bas:4:7 - You didn't specify a valid number!

   ║  
 4 ║  error "You didn't specify a valid number!"
   ║         │
   ║         └─ You didn't specify a valid number! (4:7)

  at if block (line 3)
  at engine [EXECUTE] (line 1)
```

While entering a valid number will allow the program to continue:

```
Enter a number: 1
1 x 2 = 2
```

## 2.7. STOP!

The `STOP` keyword is very similar to the `ERROR` keyword, in that it stops the program, the only difference being that it doesn't end violently with an error. Let's look at the following file:

```
print "hello"
stop
print " world"
```

Running this will only echo "hello" to the user, because the program is stopped right before "world" can be echoed. Let's run it:

```
user: U:/Home/Desktop $ basic hello.bas

hello

user: U:/Home/Desktop $
```

As you can see, only the first half of our amazing message was echoed to the user. Such a cliffhanger, wouldn't you agree?

## 3. Advanced BASIC

Now we're getting into the weeds. Subroutines, environment variables, file reading, you name it. Let's start simple: environment variables!

### 3.1. Environment variables

Sacruda has several environment variables that tell processes and applications about important information. Everything from which PID the User Daemon is running on to what your name is, is in the environment variables. These variables are kept safe and sound in a kernel module known as `env`. We can use the `ENV()` function to get the value of an environment variable. For example, to get the current user's username, let's use the following code:

```
var name = env("CURRENTUSER")
print "Hello, $name!"
```

Running this code gives us the following result:

```
user: U:/Home/Desktop $ basic hello.bas

Hello, user!

user: U:/Home/Desktop $
```

### 3.2. Mathematics

You may have seen the `MATH()` function be used throughout the guides. The `MATH()` function is a *very* powerful tool that can be used to do all kinds of fun things. It's powered by [math.js](https://mathjs.org/docs/index.html), a very useful library that neatly integrates into Sacruda BASIC. Here are a few examples of what you can do with the `MATH()` function:

#### a. Random number generator

```
var num = math(floor(random() * 10))
var guess = -1

print "I've generated a random number between 0 and 10. What is it?\n"

while $guess neq $num do
  if $guess neq -1 then
    print "\nWrong! Try again..."
  endif

  var guess = INPUT("Your guess: ")
endwhile

print "\nCorrect! Well done."
```

First, we're using the `MATH()` function with, [`random()`](https://mathjs.org/docs/reference/functions/random.html) to generate a random number between 0 and 1, which we then multiply by 10, after which we use [`floor()`](https://mathjs.org/docs/reference/functions/floor.html) to round the value, removing the decimals.

Then, we're looping endlessly until the user's guess matches the number that we've generated. In this loop, if the user has guessed something, so if the variable no longer holds the default value of `-1`, we print that their guess was wrong before once again asking them for their guess.

Finally, after the loop, we echo to the user that they've successfully guessed the number.

Running this code will give you the following result:

```
user: U:/Home/Desktop $ basic guess.bas

I've generated a random number between 0 and 10. What is it?

Your guess: 5

Wrong! Try again...
Your guess: 3

Wrong! Try again...
Your guess: 9

Wrong! Try again...
Your guess: 8

Correct! Well done.

user: U:/Home/Desktop $
```

#### b. Plugging variables in

We can also neatly plug Sacruda BASIC variables into the `MATH()` function, just like any other function. These are turned into their real values before they're sent off to `math.js` to actually perform the calculation. Take the following example:

```
var a = 10
var b = 5

print math($a * $b)
```

This will echo a value of `50` to the user.

#### c. Binary!

You can also print regular numbers as binary to the console using the [`bin()`](https://mathjs.org/docs/reference/functions/bin.html) function:

```
print math(bin(15))
```

This will echo a value of `0b1111` to the user.

## \[TO BE CONTINUED]
