BazzBasic_AI_Guide / BazzBasic-AI-guide-07052026.txt
EkBass's picture
Upload BazzBasic-AI-guide-07052026.txt
1b1d1d7 verified
---
name: bazzbasic
description: "BazzBasic BASIC interpreter language reference. Use when writing, debugging, or explaining BazzBasic code (.bas files). Triggers on: BazzBasic syntax, $ and # variable suffixes, SDL2 graphics in BASIC, SCREEN/DRAWSHAPE/LOADIMAGE commands, DEF FN functions, BazzBasic file I/O, sound commands, or any question about BazzBasic features. Always use this skill before writing any BazzBasic code."
doc. date: 06.05.2026 (dd.mm.yyyy)
filename: BazzBasic-AI-guide-ddmmyyyyX.txt (ddmmyyyy = date of last update) (X is small alphabet "abcd..." presenting daily version incase two versions are released in same day)
IE:
BazzBasic-AI-Guide30042026.txt ' version released 30th April 2026
BazzBasic-AI-Guide30042026b.txt ' version released 30th April 2026, second in same date
---
# BazzBasic Language Reference
**Version:** 1.4 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64
**Homepage:** https://ekbass.github.io/BazzBasic/
**GitHub:** https://github.com/EkBass/BazzBasic
**Manual:** https://ekbass.github.io/BazzBasic/manual/#/
**Examples:** https://github.com/EkBass/BazzBasic/tree/main/Examples
**Rosetta Code:** https://rosettacode.org/wiki/Category:BazzBasic
**Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
**BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
**BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
**Communities:** https://ekbass.github.io/BazzBasic/communities.html
---
## Critical Rules Read First
| Rule | Detail |
|------|--------|
| Variables end with `$` | `name$`, `score$`, `x$` |
| Constants end with `#` | `MAX#`, `PI#`, `TITLE#` |
| Arrays declared with `DIM`, end with `$` | `DIM items$` |
| First use of variable requires `LET` | `LET x$ = 0` after that `x$ = x$ + 1` |
| FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
| Functions defined **before** they are called | Put at top or INCLUDE |
| Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
| Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
| Arrays **cannot** be passed to functions directly | Pass individual elements, or serialize to JSON string see *Passing Arrays to Functions* section |
| Case-insensitive | `PRINT`, `print`, `Print` all work |
| `+` operator does both add and concatenate | `"Hi" + " " + name$` |
| Division always returns float | `10 / 3` → `3.333...` |
| Division by zero returns `0` (no error) | Guard with `IF b$ = 0 THEN ...` if needed |
| No integer-division operator | Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` |
| Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` line-numbered message printed |
| Declare variables inside of [inits] at begin of code. Not inside [sub:xxx], since it slows BazzBasic |
---
## Common AI Mistakes (avoid these)
These are the patterns LLMs most often produce when extrapolating from QBASIC, FreeBASIC, or VB. None of them are valid BazzBasic.
```basic
' WRONG ' CORRECT
LET x = 5 LET x$ = 5
LET MAX = 10 LET MAX# = 10
score$ = 0 ' first use LET score$ = 0
DEF FN doStuff(a, b) DEF FN DoStuff$(a$, b$)
FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + STR(x$), 10, 10, RGB(255,255,255)
FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
ISSET(arr$(0)) ' expecting error ' returns 0 silently ISSET only sees scalars
LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren see Line Continuation
```
**Two more traps that don't fit the table:**
- Inside `DEF FN` you can read `#` constants from the outer scope but **not** `$` variables. Pass them as parameters.
- Arrays cannot be passed to a function. Serialize with `ASJSON()` and rebuild inside the function with `ASARRAY()` see *Passing Arrays to Functions* below.
---
## Minimal Valid Program
```basic
' User-defined functions first
[inits]
' constants
LET MY_CONST# = 123
' variables
LET name$ = "World"
LET foo$ ' declare also variables even they are assigned later to speed up the process
[main]
foo$ = 123
PRINT "Hello, " + name$
PRINT foo$
END
```
Programs flow top to bottom. `[inits]` and `[main]` are organizational labels, not required syntax the file would also run without them. `END` halts execution; place it at the end of the main flow so control doesn't fall through into subroutines or function definitions.
---
## When Generating BazzBasic Code
- Always declare variables with `LET` on first use; subsequent uses don't need it
- Always include the `$` (variable) or `#` (constant) suffix
- Place `DEF FN` definitions at the top of the file or via `INCLUDE`
- Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant
- In graphics mode, prefer `LINE (0,0)-(W,H), 0, BF` over `CLS`, and `DRAWSTRING` over `PRINT`
- Wrap each frame's drawing in `SCREENLOCK ON` / `SCREENLOCK OFF`
- Always use a function's return value assign with `LET` or consume with `PRINT` or `IF`
- If a feature isn't documented in this guide, say so rather than inventing one BazzBasic does not silently inherit QBASIC, FreeBASIC, or VB conventions
- Declare variables at start, inside of [inits] when ever possible. Inside of [sub:xxx] 'LET' just wastes time since BazzBasic has to check if variable is declared already.
---
## ABOUT
BazzBasic is built around one simple idea: starting programming should feel nice and even fun. Ease of learning, comfort of exploration and small but important moments of success. Just like the classic BASICs of decades past, but with a fresh and modern feel.
### What people have built with it
BazzBasic is built for beginners, but it isn't a toy. It can carry real 2D games and even 2.5D graphics work.
- https://github.com/EkBass/BazzBasic/blob/main/Examples/Voxel_terrain.bas
A Comanche-style heightmap renderer with procedurally generated terrain. Eight smoothing passes turn random noise into hills, valleys, water, beaches, forests, rock, and snow each assigned a color by height band.
- https://github.com/EkBass/BazzBasic/blob/main/Examples/Raycaster_3d_optimized.bas
A smooth first-person raycaster engine written entirely in BazzBasic. Minimap, depth shading and real-time movement proves that BazzBasic can handle serious graphics work.
- https://ek-bass.itch.io/rgb-vision
A speedrun platformer made for Jam for All BASIC Dialects #7 (itch.io).
- https://github.com/EkBass/BazzBasic/blob/main/Examples/2D_maze_FOV_demo_console.bas
2D maze with FOV in your console
- https://ek-bass.itch.io/eliza-bazzbasic-edition
A classic DOCTOR script from the 60s which made people honestly believe they are talking to a real human. Grandmother of modern AIs.
- https://github.com/EkBass/BazzBasic/blob/main/Examples/rosetta-code/BrainFuck.bas
BrainFuck interpreter. One of the first programs ever done with BazzBasic.
- https://github.com/EkBass/BazzBasic/blob/main/Examples/Anthropic_Claude_API_call.bas & https://github.com/EkBass/BazzBasic/blob/main/Examples/OpenAI_request.bas
Anthropic Claude API and OpenAI ChatGPT API available, both with less than 50 lines of code.
**Note:** All ".../Examples/..." codes are delivered with BazzBasic and they are found on the BazzBasic executable folder.
### STORY
Although over the years, as my own skills have grown, I have moved on to more versatile and modern languages, BASIC has always been something that has been fun to try out many different things with. Sometimes it's great to just make a simple adventure game again, a lottery machine, a quiz, or even just those balls bouncing on the screen. BazzBasic was created with this in mind. I wanted to create a language that makes it easy for you to give free rein to your curiosity and program something. And when you finish your first little game, you may crave something bigger and better. Maybe one day you will move on to another programming language, but then BazzBasic will have succeeded in doing what it was intended for.
To arouse your curiosity.
*EkBass*, author of BazzBasic
---
## Case sensitivity
BazzBasic is not case-sensitive except with string contents.
```basic
let blaa$ = "Hello"
PriNT BLAA$ ' output: Hello
```
---
## Line Continuation
BazzBasic has **no line-continuation character**. Do not generate `_` (VBA), `\` (Python), or `&` (other dialects). The lexer figures out continuation automatically using two rules.
**Rule 1 operator at end of line.** If a line ends in a token that cannot legally end an expression, the next line continues it:
```basic
LET total$ = price$ * count$ -
discount$
IF score$ >= 0 AND
score$ <= 100 THEN
PRINT "Valid"
END IF
LET counter$ +=
step$
```
Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
> `MOD` is a function `MOD(a, b)`, not a binary operator it does not trigger continuation. Use `%` for the modulo operator.
**Rule 2 open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
```basic
LET dist$ = DISTANCE(
x1$, y1$,
x2$, y2$
)
```
Both rules combine:
```basic
LET total$ = (
base$ +
tax$
)
```
**Trap for AI generators.** Do NOT emit a trailing `_`, `\`, `&`, or any other continuation marker they are not BazzBasic syntax and will produce parse errors. Just leave the operator at the end of the line, or open a paren.
---
## Variables & Constants
Variables and constants must be declared with LET before they can be used.
BazzBasic variables are not typed, but work the same way as in JavaScript, for example.
A variable needs the suffix $ which often is linked as STRING in traditional basic variants.
Variables require suffix "$". Constants require suffix "#".
The suffix does not define data type only "#" indicates immutability.
```basic
LET a$ ' Declare variable without value
LET b$, c$, d$ ' Multiple variable declarations without value
LET e$, f$ = "foo", g$ = 10 ' Multiple variable declaration, e$ stays empty, f$ and g$ gets values
LET name$ = "Alice" ' String variable
LET score$ = 0 ' Numeric variable
LET PI# = 3.14159 ' Constant (immutable)
LET TITLE# = "My Game" ' String constant
```
**Compound assignment operators** (variables only **not** allowed with `#` constants):
```basic
LET x$ = 1
x$ += 5 ' add
x$ -= 3 ' subtract
x$ *= 2 ' multiply
x$ /= 4 ' divide
LET s$ = "Hello"
s$ += " World" ' string concatenation
```
**Scope:** All main-code variables share one scope (IF, FOR, and WHILE do NOT create new scope).
Main-code variables ($) are NOT accessible inside DEF FN
`DEF FN` functions are fully isolated only global constants (`#`) accessible inside.
**Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
---
### Built-in Constants
- **Boolean:** `TRUE`, `FALSE` ' These two does not require suffix '#'
- **Math:** `PI#`, `HPI#` (PI#/2), `QPI#` (PI#/4), `TAU#` (PI# * 2), `EULER#` (e) `#` suffix required
- **System:** `PRG_ROOT#` (program base directory path)
- **Keyboard:** `KEY_ESC#`, `KEY_ENTER#`, `KEY_SPACE#`, `KEY_UP#`, `KEY_DOWN#`, `KEY_LEFT#`, `KEY_RIGHT#`, `KEY_F1#`…`KEY_F12#`, `KEY_A#`…`KEY_Z#`, `KEY_0#`…`KEY_9#`, `KEY_LSHIFT#`, `KEY_LCTRL#`, etc.
---
## Arrays
BazzBasic arrays are fully dynamic and support numeric, string, or mixed indexing.
```basic
DIM scores$ ' Declare (required before use)
DIM a$, b$, c$ ' Multiple
scores$(0) = 95 ' Numeric indices are 0-based.
scores$("name") = "Alice" ' String keys are associative and unordered.
matrix$(0, 1) = "A2" ' Multi-dimensional
DIM sounds$
sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
sounds$("guns", "shotgun_reload") = "reload_shotgun.wav"
sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
sounds$("guns", "ak47_reload") = "reload_ak47.wav"
sounds$("food", "ham_eat") = "eat_ham.wav"
PRINT LEN(sounds$()) ' 5 as full size of arrayas there is total of 5 values in array
PRINT ROWCOUNT(sounds$()) ' 2, "guns" & "food"
```
| Function/Command | Description |
|-----------------|-------------|
| `LEN(arr$())` | Total element count (LEN counts all nested elements across all dimensions) |
| `ROWCOUNT(arr$())` | Count of first-dimension rows use this for FOR loops over multi-dim arrays |
| `HASKEY(arr$(key))` | 1 if exists, 0 if not |
| `DELKEY arr$(key)` | Remove one element |
| `DELARRAY arr$` | Remove entire array (can re-DIM after) |
| `JOIN dest$, src1$, src2$` | Merge two arrays; `src2$` keys overwrite `src1$`. Use empty `src1$` as `COPYARRAY`. |
**JOIN** Matching keys from src2$ overwrite src1$ at the same level
**Always check with `HASKEY` before reading uninitialized elements.**
---
## Control Flow
```basic
' Block IF
IF score$ >= 90 THEN
PRINT "A"
ELSEIF score$ >= 80 THEN
PRINT "B"
ELSE
PRINT "F"
END IF ' ENDIF also works
' One-line IF
IF lives$ = 0 THEN GOTO [game_over]
IF key$ = KEY_ESC# THEN GOTO [menu] ELSE GOTO [play]
' FOR (auto-declares variable)
FOR i$ = 1 TO 10 STEP 2 : PRINT i$ : NEXT
FOR i$ = 10 TO 1 STEP -1 : PRINT i$ : NEXT
' WHILE
WHILE x$ < 100
x$ = x$ * 2
WEND
' Labels, GOTO, GOSUB
[start]
GOSUB [sub:init]
' Avoid jumping into the middle of logical blocks (e.g. inside IF/WHILE)
GOTO [start]
[sub:init]
LET x$ = 0
RETURN
' Dynamic jump (variable must contain "[label]" with brackets)
LET target$ = "[menu]"
GOTO target$
' Other
SLEEP 2000 ' Pause for milliseconds
END ' Terminate program
```
**Note:** Labels are case-insensitive and may contain almost any printable character.
Whitespace is trimmed. Everything between "[" and "]" is treated as the label name.
---
## I/O
| Command | Description |
|---------|-------------|
| `PRINT expr; expr` | `;` = no space, `,` = tab |
| `PRINT "text";` | Trailing `;` suppresses newline |
| `INPUT "prompt", var$` | Splits on whitespace/comma |
| `INPUT "prompt", a$, b$` | Multiple values |
| `LINE INPUT "prompt", var$` | Read entire line with spaces |
| `CLS` | Clear screen |
| `LOCATE row, col` | Move cursor (1-based) |
| `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
| `CURPOS()` | Read cursor as `"row,col"` string |
| `COLOR fg, bg` | Text colors (0-15 palette) |
| `SHELL("cmd")` | Run shell command, returns output |
| `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
' ; prints without spacing
' , prints tab separation
' Both can be mixed in a single PRINT statement
' INPUT splits on whitespace and comma; quoted strings are treated as single values
**Escape sequences in strings:** `\"` `\n` `\t` `\\`
**SHELL + SQLite.** SQLite (the `sqlite3` CLI tool) is the recommended way to add a real database to a BazzBasic script — see the *SQLite Database* page in the manual for the full guide. Three things to remember when generating SHELL commands that wrap SQL:
- Always append `2>&1` to the command, or SQL errors disappear silently.
- Use `\"` (BazzBasic escape) to wrap the SQL for the OS shell: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
- In paths use `/` or `\\` — never a single `\`.
### Keyboard Input
| Function | Returns | Notes |
|----------|---------|-------|
| `INKEY` | Key value or 0 | Non-blocking |
| `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection; KEYDOWN only works in graphics mode |
| `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
### Mouse (graphics mode only)
`MOUSEX`, `MOUSEY` cursor position
`MOUSELEFT`, MOUSERIGHT, MOUSEMIDDLE return 1 if pressed, 0 otherwise
`MOUSEHIDE` hide the mouse cursor (graphics screen only)
`MOUSESHOW` restore the mouse cursor (graphics screen only)
### Console Read
Returns numeric or character depending on type parameter
`GETCONSOLE(row, col, type)` type: 0=char (ASCII), 1=fg color, 2=bg color
---
## User-Defined Functions
```basic
' Define BEFORE calling. Name must end with $.
DEF FN Clamp$(val$, lo$, hi$)
IF val$ < lo$ THEN RETURN lo$
IF val$ > hi$ THEN RETURN hi$
RETURN val$
END DEF
PRINT FN Clamp$(5, 1, 10) ' OK return value used
LET v$ = FN Clamp$(15, 0, 10) ' OK
FN Clamp$(5, 1, 10) ' ERROR return value unused
' Return value must be assigned with LET or consumed by PRINT there is no way to silently discard it.
```
- Isolated scope: no access to global variables, only global constants (`#`)
- Parameters passed **by value**
- Labels inside functions are local GOTO/GOSUB cannot jump outside
- Supports recursion
- Arrays as parameters not allowed. Use ASJSON to make array as JSON-string to pass it.
- Use `INCLUDE` to load functions from separate files if many
---
## String Functions
| Function | Description |
|----------|-------------|
| `ASC(s$)` | ASCII code of first char |
| `CHR(n)` | Character from ASCII code |
| `FSTRING(template$)` | String interpolation with `{{-name-}}` placeholders. See dedicated FSTRING section below for full syntax. |
| `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive by default |
| `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
| `INSTR(start, s$, search$)` | Search from position (case-sensitive) |
| `INVERT(s$)` | Reverse string |
| `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
| `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars |
| `LEN(s$)` | String length |
| `LTRIM(s$)` / `RTRIM(s$)` / `TRIM(s$)` | Strip whitespace |
| `MID(s$, start)` | Substring from start (1-based) |
| `MID(s$, start, len)` | Substring with length |
| `REPEAT(s$, n)` | Repeat string n times |
| `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
| `SPLIT(arr$, s$, sep$)` | Split into array, returns count. Expects array is declared with DIM |
| `SRAND(n)` | Random alphanumeric string of length n |
| `STR(n)` | Number to string |
| `VAL(s$)` | String to number |
| `SHA256(s$)` | SHA256 hash (64-char hex) |
| `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
---
## FSTRING - String Interpolation
`FSTRING(template$)` substitutes `{{-name-}}` placeholders inside a template
string with the value of variables, constants, or array elements. It is the
recommended alternative to long `+` concatenation chains.
```basic
LET name$ = "Krisu"
LET LEVEL# = 5
PRINT FSTRING("Hello {{-name$-}}, level {{-LEVEL#-}}")
' Output: Hello Krisu, level 5
```
### Why the `{{-...-}}` markers?
The triple-character markers `{{-` and `-}}` are deliberately unusual so they
will not collide with normal text inside a string. There is no escape syntax;
if a template contains literal `{{-...-}}`, FSTRING will always try to resolve
it as a placeholder.
### Placeholder forms
| Form | Resolves to |
|------|-------------|
| `{{-var$-}}` | Value of variable `var$` |
| `{{-CONST#-}}` | Value of constant `CONST#` |
| `{{-arr$(0)-}}` | Array element at numeric index `0` |
| `{{-arr$(i$)-}}` | Array element at index taken from variable `i$` |
| `{{-arr$(KEY#)-}}` | Array element at index taken from constant `KEY#` |
| `{{-arr$(name)-}}` | Array element at literal string key `"name"` (no quotes inside FSTRING) |
| `{{-arr$(0, i$)-}}` | Multidimensional element, mixed literal and variable indices |
### Index resolution rule (for array access)
For each comma-separated index, FSTRING decides what it is by looking at the
last character:
1. Ends with `$` or `#` -> treat as variable / constant lookup. Halts with an
error if the name is not defined.
2. Parses as a number (`0`, `1.5`, `-3`) -> treat as a numeric index. The
number is normalised through a double round-trip so `arr$(01)` and
`arr$(1.0)` both find the key `1`.
3. Otherwise -> treat as a literal string key. This is what lets you write
`{{-player$(name)-}}` to read what was stored with `player$("name") = ...`.
### Whitespace inside placeholders
All whitespace inside a placeholder is trimmed, so these are equivalent:
```basic
FSTRING("{{-name$-}}")
FSTRING("{{- name$ -}}")
FSTRING("{{- name$ -}}")
FSTRING("{{- arr$( 0 , i$ ) -}}")
```
### Numbers auto-stringify
Both numeric variables / constants and array elements that hold numbers are
converted to strings automatically (no `STR()` needed):
```basic
LET score$ = 42
LET pi# = 3.14159
PRINT FSTRING("Score: {{-score$-}}, Pi: {{-pi#-}}")
' Output: Score: 42, Pi: 3.14159
```
### What is NOT supported (intentional)
These are out of scope; FSTRING is meant to stay simple and predictable. Use
a normal variable to pre-compute, then reference that variable in FSTRING.
```basic
' WRONG: arithmetic inside placeholder
PRINT FSTRING("Total: {{-a$ + 5-}}")
' WRONG: function call inside placeholder
PRINT FSTRING("Name: {{-UCASE(name$)-}}")
' WRONG: nested array lookup inside placeholder
PRINT FSTRING("{{-arr$(arr2$(0))-}}")
' WRONG: string literal with quotes inside placeholder
PRINT FSTRING("{{-arr$(\"name\")-}}")
```
```basic
' RIGHT: pre-compute, then reference
LET total$ = a$ + 5
LET upper$ = UCASE(name$)
LET k$ = arr2$(0)
PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
```
### Errors halt execution
Like other BazzBasic errors, these print a line-numbered message and stop
the program:
- `FSTRING: undefined variable 'foo$'.`
- `FSTRING: undefined variable 'i$' in array index of 'arr$(i$)'.`
- `FSTRING: missing closing '-}}' in template.`
- `FSTRING: empty placeholder '{{--}}'.`
- `FSTRING: malformed array access '...'.`
- `FSTRING: Array element ...(...) not initialized` (the standard array error,
prefixed with FSTRING).
### Common AI mistakes with FSTRING
```basic
' WRONG: forgot the dashes
LET s$ = FSTRING("Hi {{name$}}")
' WRONG: only one brace pair
LET s$ = FSTRING("Hi {-name$-}")
' WRONG: $ suffix omitted in placeholder
LET s$ = FSTRING("Hi {{-name-}}")
' This compiles but treats `name` as a literal key for an array lookup.
' If `name` is intended as a variable, write `{{-name$-}}`.
' WRONG: using FSTRING as a statement
FSTRING("Hi {{-name$-}}")
' FSTRING returns a value; you must use it: LET / PRINT / pass to function.
' RIGHT
LET s$ = FSTRING("Hi {{-name$-}}, level {{-LEVEL#-}}")
PRINT FSTRING("Score: {{-score$-}}")
```
### Full working example
```basic
DIM player$
player$("name") = "Krisu"
player$("class") = "Bass"
player$("level") = 99
DIM grid$
grid$(0, 0) = "X"
grid$(0, 1) = "O"
grid$(1, 0) = "."
grid$(1, 1) = "X"
LET row$ = 1
LET PI# = 3.14
PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
PRINT FSTRING("Pi is roughly {{-PI#-}}")
END
```
Output:
```
Krisu the Bass, lvl 99
Row 1: [.X]
Pi is roughly 3.14
```
---
## Math Functions
| Function | Description |
|----------|-------------|
| `ABS(n)` | Absolute value |
| `ATAN(n)` | Arc tangent |
| `ATAN2(x, y)` | Returns the angle, in radians, between the positive x-axis and a vector to the point with the given (x, y) coordinates in the Cartesian plane |
| `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
| `INBETWEEN(n, min, max)` | TRUE if min < n < max (strictly between, not equal) |
| `CEIL(n)` / `FLOOR(n)` | Round up / down |
| `CINT(n)` | Round to nearest integer |
| `CLAMP(n, min, max)` | Constrain n to [min, max] |
| `COS(n)` / `SIN(n)` / `TAN(n)` | Trig (radians) |
| `DEG(rad)` / `RAD(deg)` | Radians ↔ degrees |
| `DISTANCE(x1,y1, x2,y2)` | 2D Euclidean distance |
| `DISTANCE(x1,y1,z1, x2,y2,z2)` | 3D Euclidean distance |
| `EXP(n)` | e^n |
| `INT(n)` | Truncate toward zero |
| `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
| `LOG(n)` | Natural logarithm |
| `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
| `MOD(a, b)` | Remainder |
| `POW(base, exp)` | Power |
| `RND(n)` | Random integer 0 to n-1 if n > 0 |
| `RND(0)` | Float between 0.0 and 1.0 (IE: 0.5841907423666761) |
| `ROUND(n)` | Standard rounding |
| `SGN(n)` | Sign: -1, 0, or 1 |
| `SQR(n)` | Square root |
**Math constants:** `PI#`, `HPI#` (PI/2), `QPI#` (PI/4), `TAU#` (PI*2), `EULER#`
---
## Variable Functions
| Function | Description |
|----------|-------------|
| `ISSET(name)` | `1` if the named variable (`$`) or constant (`#`) is declared, `0` otherwise. Argument is **not evaluated** `ISSET(undef$)` safely returns `0`. |
`ISSET` is the only language-introspection function and it has tight rules:
- **Scalars only.** Variables (`$`) and constants (`#`). Arrays and array
elements are stored separately `ISSET(arr$)` and `ISSET(arr$(0))` always
return `0`, never an error.
- **Bare name only.** No expressions, no string literals, no numbers. These
all error with "invalid parameter":
```basic
ISSET(a$ + b$) ' WRONG: expression
ISSET("a$") ' WRONG: string literal
ISSET(42) ' WRONG: number
ISSET() ' WRONG: empty
```
- **Suffix is part of the name.** `a$` and `A#` are different names:
```basic
LET a$ = "foo"
PRINT ISSET(a$) ' 1
PRINT ISSET(A#) ' 0
```
- **`LET name$` (no value) still counts as set.** `LET` always registers the
variable; the value just defaults to empty string for `$` and zero for
numeric. `ISSET` reports declaration, not "has a meaningful value".
Typical use is guarding optional setup:
```basic
IF NOT ISSET(playerName$) THEN
LET playerName$ = "Anonymous"
END IF
```
---
## Graphics
```basic
SCREEN 12 ' 640×480 VGA
SCREEN 0, 800, 600 ' Custom size
SCREEN 0, 1024, 768, "My Game" ' Custom size + title
FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
FULLSCREEN FALSE ' Windowed
```
| Mode | Resolution |
|------|-----------|
| 1 | 320×200 |
| 2 | 640×350 |
| 7 | 320×200 |
| 9 | 640×350 |
| 12 | 640×480 ← recommended |
| 13 | 320×200 |
### Drawing Primitives
```basic
PSET (x, y), color ' Pixel
LINE (x1,y1)-(x2,y2), color ' Line
LINE (x1,y1)-(x2,y2), color, B ' Box outline
LINE (x1,y1)-(x2,y2), color, BF ' Box filled (FAST use instead of CLS)
CIRCLE (cx,cy), radius, color ' Circle outline
CIRCLE (cx,cy), radius, color, 1 ' Circle filled
PAINT (x, y), fillColor, borderColor ' Flood fill
LET c$ = POINT(x, y) ' Read pixel color
LET col$ = RGB(r, g, b) ' Create color (0–255 each)
```
**Color palette (COLOR command, 0–15):** 0=Black, 1=Blue, 2=Green, 3=Cyan, 4=Red, 5=Magenta, 6=Brown, 7=Lt Gray, 8=Dk Gray, 9=Lt Blue, 10=Lt Green, 11=Lt Cyan, 12=Lt Red, 13=Lt Magenta, 14=Yellow, 15=White
### Screen Control
```basic
SCREENLOCK ON ' Buffer drawing (start frame)
SCREENLOCK OFF ' Present buffer (end frame)
VSYNC(TRUE) ' Enable VSync (default, ~60 FPS)
VSYNC(FALSE) ' Disable VSync (benchmarking)
CLS ' Clear screen
' Use CLS only with console, in graphics screen its slow
' With graphics screen, prefer LINE BF
```
### Shapes & Images
```basic
' Create shape
' LOADSHAPE and LOADIMAGE return a stable integer handle never reassigned.
' SDL2 owns the resource; your code only ever holds this one reference. Use constants.
LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
' Sprite sheet sprites indexed 1-based
DIM sprites$
LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
MOVESHAPE sprites$(1), x, y ' sprites$(1) = first sprite
' Transform
MOVESHAPE RECT#, x, y ' Position by top-left
ROTATESHAPE RECT#, angle ' Degrees (absolute)
SCALESHAPE RECT#, scale ' 1.0 = original size
DRAWSHAPE RECT# ' Render to buffer
SHOWSHAPE RECT# / HIDESHAPE RECT# ' Toggle visibility
REMOVESHAPE RECT# ' Free memory (always clean up)
```
---
### Text Rendering (SDL2_ttf.dll required)
#### DRAWSTRING & LOADFONT
```basic
' Default font (Arial)
DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
' Load alternative font becomes the new default
LOADFONT "comic.ttf", 24
DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
' Reset to Arial
LOADFONT
```
`DRAWSTRING x, y` positions the top-left of the text. Requires `SDL2_ttf.dll` in the same directory as the interpreter. Prefer this over PRINT, which makes graphic screen easily blinking.
---
## Sound
```basic
' LOADSOUND returns a stable integer handle SDL2 manages the resource.
' The handle never changes; store it in a constant to protect it from accidental reassignment.
LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
SOUNDREPEAT(SND_JUMP#) ' Loop continuously
SOUNDSTOP(SND_JUMP#) ' Stop specific sound
SOUNDSTOPALL ' Stop all sounds
```
Load all sounds at startup. Call `SOUNDSTOPALL` before `END`.
---
## File I/O
```basic
LET data$ = FILEREAD("file.txt") ' Read as string
DIM cfg$ : LET cfg$ = FILEREAD("settings.txt") ' Read as key=value array
FILEWRITE "save.txt", data$ ' Create/overwrite
FILEAPPEND "log.txt", entry$ ' Append
LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
FILEDELETE "temp.dat" ' Delete file
```
**key=value parsing:** When `FILEREAD` assigns to a `DIM`'d array, lines `key=value` become `arr$("key")`. Lines starting with `#` are comments. Perfect for `.env` files.
```basic
DIM env$
LET env$ = FILEREAD(".env")
LET API_KEY# = env$("OPENAI_API_KEY")
```
**Paths:** Use `/` or `\\` never single `\` (it's an escape char). Relative paths are from `PRG_ROOT#`.
**FILEWRITE with array** saves in key=value format (round-trips with FILEREAD).
---
## Network
```basic
LET res$ = HTTPGET("https://api.example.com/data")
LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
' With headers (optional last parameter)
DIM headers$
headers$("Authorization") = "Bearer mytoken"
headers$("Content-Type") = "application/json"
LET res$ = HTTPGET("https://api.example.com/data", headers$)
LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
```
### Local HTTP server (LISTEN)
BazzBasic can also receive requests as a local-only HTTP server, typically used as glue between a static HTML page and a BazzBasic script on the same machine.
```basic
STARTLISTEN 8080 ' bind 127.0.0.1:8080, no admin needed
STARTLISTEN 8080, 5000 ' optional timeout in ms
LET body$ = GETREQUEST() ' POST/PUT/PATCH body, or GET query string ("" on timeout)
SENDRESPONSE "{""status"":""ok""}" ' must be called or browser hangs
STOPLISTEN
```
Important rules:
- **Always pair `GETREQUEST()` with `SENDRESPONSE`.** The browser is waiting on the response. Forgetting `SENDRESPONSE` makes the page hang.
- **Bound to `127.0.0.1` only.** This is local glue, not a real web server. Do not generate code that tries to expose this on the LAN or internet.
- **Body or query string, not full request.** `GETREQUEST()` returns just the POST body (or the GET query string without `?`). Headers, method, and URL path are NOT exposed in this version. If you need structured data, parse the body with `ASARRAY(body$)`.
- **OPTIONS preflight is automatic.** Do NOT write code that handles `OPTIONS` it is consumed silently and never reaches user code.
- **CORS is automatic.** Every response carries `Access-Control-Allow-Origin: *`. No need to set it manually.
- **One listener at a time.** Calling `STARTLISTEN` while one is already active is an error. Call `STOPLISTEN` first.
- **Always 200 OK, always `text/plain`.** Custom status codes and content types are not supported in this version. To return JSON, just put JSON text in the body browser-side `response.json()` still works.
Typical receive-and-process pattern:
```basic
STARTLISTEN 8080
PRINT "Waiting for browser..."
LET json$ = GETREQUEST()
DIM data$
LET data$ = ASARRAY(json$)
PRINT "Got name: " + data$("name")
SENDRESPONSE "{""status"":""ok""}"
STOPLISTEN
END
```
---
## Arrays & JSON
Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`
```basic
' Array → JSON string
LET json$ = ASJSON(arr$)
' JSON string → array (returns element count)
DIM data$
LET count$ = ASARRAY(data$, json$)
' Load/save JSON files
LOADJSON arr$, "file.json"
SAVEJSON arr$, "file.json"
```
---
## Fast Trigonometry
~20× faster than `SIN(RAD(x))`, 1-degree (integer) precision. Uses ~5.6 KB memory.
```basic
FastTrig(TRUE) ' Enable lookup tables (must call first)
LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
LET y$ = FastSin(90)
LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
FastTrig(FALSE) ' Free memory
```
Use for raycasting, sprite rotation, particle systems, any high-freq trig.
---
## Command-Line Arguments
```basic
' bazzbasic.exe myprog.bas arg1 arg2
PRINT ARGCOUNT ' number of args (2 in this example)
PRINT ARGS(0) ' first arg → "arg1"
PRINT ARGS(1) ' second arg → "arg2"
```
`ARGCOUNT` and `ARGS(n)` are 0-based; ARGS does not include the interpreter or script name.
---
## Libraries & INCLUDE
```basic
INCLUDE "helpers.bas" ' Insert source at this point
INCLUDE "MathLib.bb" ' Load compiled library
' Compile library (functions only no loose code)
' bazzbasic.exe -lib MathLib.bas → MathLib.bb
' Function names auto-prefixed: MATHLIB_functionname$
PRINT FN MATHLIB_add$(5, 3)
```
Library functions can read main-program constants (`#`). `.bb` files are version-locked.
---
## Passing Arrays to Functions
Arrays cannot be passed directly to `DEF FN` functions, but a clean workaround exists using JSON serialization. Convert the array to a JSON string with `ASJSON`, pass the string as a parameter, then deserialize inside the function with `ASARRAY`. This is the accepted pattern in BazzBasic v1.2+.
```basic
DEF FN ProcessPlayer$(data$)
DIM arr$
LET count$ = ASARRAY(arr$, data$)
RETURN arr$("name") + " score:" + arr$("score")
END DEF
[inits]
DIM player$
player$("name") = "Alice"
player$("score") = 9999
player$("address,city") = "New York"
[main]
LET json$ = ASJSON(player$)
PRINT FN ProcessPlayer$(json$)
END
```
**Notes:**
- The function receives a full independent copy changes inside do not affect the original array
- Nested keys work normally: `arr$("address,city")` etc.
- Overhead is similar to copying an array manually; acceptable for most use cases
---
## Program Structure
```basic
' ---- 1. FUNCTIONS (or INCLUDE "functions.bas/bb") ----
DEF FN Clamp$(v$, lo$, hi$)
IF v$ < lo$ THEN RETURN lo$
IF v$ > hi$ THEN RETURN hi$
RETURN v$
END DEF
' ---- 2. INIT (declare ALL constants & variables here, not inside loops) ----
' Performance: variables declared outside loops avoid repeated existence checks.
[inits]
LET SCREEN_W# = 640
LET SCREEN_H# = 480
LET MAX_SPEED# = 5
SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
LET x$ = 320
LET y$ = 240
LET running$ = TRUE
' ---- 3. MAIN LOOP ----
[main]
WHILE running$
IF INKEY = KEY_ESC# THEN running$ = FALSE
GOSUB [sub:update]
GOSUB [sub:draw]
SLEEP 16
WEND
SOUNDSTOPALL
END ' place at the end of main program so BazzBasic wont fall to subs in runtime
' ---- 4. SUBROUTINES (or INCLUDE "subs.bas") ----
[sub:update]
IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
RETURN
[sub:draw]
SCREENLOCK ON
LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
CIRCLE (x$, y$), 10, RGB(0, 255, 0), 1
SCREENLOCK OFF
RETURN
```
**Key conventions:**
- Variables: `camelCase$` | Constants: `UPPER_SNAKE_CASE#` | Functions: `PascalCase$`
- Labels: `[gameLoop]` for jump targets, `[sub:name]` for subroutines
- Image/sound/shape IDs are stable integer handles **always** store as constants: `LET MY_IMG# = LOADIMAGE("x.png")` never use `$` variables for these
- Group many IDs → use arrays: `DIM sprites$` / `sprites$("player") = LOADIMAGE(...)` but prefer named constants when count is small
---
## Performance Tips
- `LINE (0,0)-(W,H), 0, BF` to clear much faster than `CLS`
- Always wrap draw code in `SCREENLOCK ON` / `SCREENLOCK OFF`
- Store `RGB()` results in constants/variables don't call RGB in hot loops
- Declare all variables in `[inits]`, not inside loops or subroutines
- Use `FastTrig` for any loop calling trig hundreds of times per frame
- `SLEEP 16` in game loop → ~60 FPS
---
## Known Limitations
Things to be aware of most are deliberate design decisions, a few are practical constraints.
- **Platform: Windows x64 only.** Linux and macOS are not supported. Browser/Android are not feasible the runtime depends on SDL2 via P/Invoke.
- **Arrays cannot be passed to functions.** Use the `ASJSON` / `ASARRAY` round-trip pattern. The function receives an independent copy.
- **`DEF FN` scope is fully isolated.** Functions can read global `#` constants but cannot see any `$` variables from the outer scope. Pass values as parameters.
- **No block scope.** `IF`, `FOR`, and `WHILE` do not create new variable scopes all main-code variables share one namespace.
- **No exception handling.** There is no `TRY`/`CATCH` and no `ON ERROR`. Runtime errors halt the program with a line-numbered message printed to the console.
- **Division by zero returns `0` silently.** No exception, no warning. Guard with `IF b$ = 0 THEN ...` when correctness matters.
- **No integer-division operator.** Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` depending on the rounding behavior you need.
- **Compiled `.bb` libraries are version-locked** to the BazzBasic build that produced them. Recompile after upgrading the interpreter.
- **`DEF FN` definitions must precede their first call** in source order. Forward references don't resolve.
---
## IDE Features (v1.4)
### New File Template
When the IDE opens with no file (or a new file), this template is auto-inserted:
```basic
' BazzBasic version {ver_num}
' https://ekbass.github.io/BazzBasic/
```
### Beginner's Guide
- **IDE:** Menu → **Help** → **Beginner's Guide** opens `https://github.com/EkBass/BazzBasic-Beginners-Guide/releases` in default browser
- **CLI:** `bazzbasic.exe -guide` or `bazzbasic.exe -help` prints URL to terminal
### Check for Updates
- **IDE:** Menu → **Help** → **Check for updated...** IDE reports if a newer version is available
- **CLI:** `bazzbasic.exe -checkupdate`
### Compile via IDE
- **Menu → Run → Compile as Exe** compiles open file to standalone `.exe` (auto-saves first)
- **Menu → Run → Compile as Library (.bb)** compiles open file as reusable `.bb` library (auto-saves first)
EOF