EkBass commited on
Commit
a657d21
·
verified ·
1 Parent(s): 2658093

Update BazzBasic-AI-guide.md

Browse files
Files changed (1) hide show
  1. BazzBasic-AI-guide.md +300 -535
BazzBasic-AI-guide.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
- name: bazzbasic
3
- 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."
4
  ---
5
 
6
  # BazzBasic Language Reference
7
- **Version:** 1.5 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64
8
  **Homepage:** https://ekbass.github.io/BazzBasic/
9
  **GitHub:** https://github.com/EkBass/BazzBasic
10
  **Manual:** https://ekbass.github.io/BazzBasic/manual/#/
@@ -13,7 +13,8 @@ description: "BazzBasic BASIC interpreter language reference. Use when writing,
13
  **Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
14
  **BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
15
  **BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
16
- **Communities:** https://ekbass.github.io/BazzBasic/communities.html
 
17
 
18
  ---
19
 
@@ -21,22 +22,26 @@ description: "BazzBasic BASIC interpreter language reference. Use when writing,
21
 
22
  | Rule | Detail |
23
  |------|--------|
24
- | Variables end with `$` | `name$`, `score$`, `x$` |
25
- | Constants end with `#` | `MAX#`, `PI#`, `TITLE#` |
26
  | Arrays declared with `DIM`, end with `$` | `DIM items$` |
27
  | First use of variable requires `LET` | `LET x$ = 0` — after that `x$ = x$ + 1` |
28
  | FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
29
- | Functions defined **before** they are called | Put at top or INCLUDE |
 
30
  | Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
31
  | Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
32
- | Arrays **cannot** be passed to functions directly | Pass individual elements, or serialize to JSON string — see *Passing Arrays to Functions* section |
33
- | Case-insensitive | `PRINT`, `print`, `Print` all work |
34
- | `+` operator does both add and concatenate | `"Hi" + " " + name$` — if either side is a string, the other is auto-converted: `"Score: " + 5` → `"Score: 5"`, no `STR()` needed |
35
  | Division always returns float | `10 / 3` → `3.333...` |
36
- | Division by zero returns `0` (no error) | Guard with `IF b$ = 0 THEN ...` if needed |
37
  | No integer-division operator | Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` |
38
  | Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` — line-numbered message printed |
39
- | No line-continuation char | Don't use `_`, `\`, or `&` — lexer continues automatically after operators or open `(` |
 
 
 
 
40
 
41
  ---
42
 
@@ -53,79 +58,51 @@ DEF FN doStuff(a, b) DEF FN DoStuff$(a$, b$)
53
  FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
54
  LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
55
  CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
56
- PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + STR(x$), 10, 10, RGB(255,255,255)
57
  FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
58
  ISSET(arr$(0)) ' expecting error ' returns 0 silently — ISSET only sees scalars
59
  LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
60
- LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren — see Line Continuation
 
61
  ```
62
 
63
- **Two more traps that don't fit the table:**
64
 
65
- - Inside `DEF FN` you can read `#` constants from the outer scope but **not** `$` variables or global arrays. Pass values as parameters.
66
- - Arrays cannot be passed to a function directly, and a function cannot see global arrays. Serialize with `ASJSON()` and rebuild inside the function with `ASARRAY()` — see *Passing Arrays to Functions* below.
 
 
 
 
 
 
 
67
 
68
  ---
69
 
70
  ## Minimal Valid Program
71
 
72
  ```basic
73
- ' Suggested style to use [subs]
74
- [inits] ' [name] is a plain jump label, not a keyword — see Control Flow
75
  LET name$ = "World"
76
 
77
  [main]
78
  PRINT "Hello, " + name$
79
  END
80
 
81
- ' other subs after END'
82
  [sub:drawScreen]
83
- ' draw
84
  RETURN
85
  ```
86
 
87
- 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.
88
-
89
- ---
90
-
91
- ## When Generating BazzBasic Code
92
-
93
- (Suffix and return-value rules are already covered in Critical Rules above — not repeated here.)
94
-
95
- - Prefer `FSTRING` over long `+` concatenation chains for multi-variable strings
96
- - Place `DEF FN` definitions at the top of the file or via `INCLUDE`
97
- - Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant
98
- - In graphics mode, prefer `LINE (0,0)-(W,H), 0, BF` over `CLS`, and `DRAWSTRING` over `PRINT`
99
- - Wrap each frame's drawing in `SCREENLOCK ON` / `SCREENLOCK OFF`
100
- - 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
101
-
102
- ---
103
-
104
-
105
- ## ABOUT
106
-
107
- BazzBasic is built around one simple idea: starting programming should feel nice, even fun — the ease and small joyful moments of the classic BASICs of decades past, with a fresh, modern feel.
108
-
109
- Over the years my own skills have grown and I've moved on to more versatile languages, but BASIC has always stayed fun for quick experiments — a simple adventure game, a lottery machine, a quiz, or just balls bouncing on the screen. BazzBasic was built with that in mind: a language that gets out of your way so curiosity can run free. And when you finish your first little game and crave something bigger, and eventually move on to another language — that's BazzBasic succeeding at exactly what it was meant to do.
110
-
111
- To arouse your curiosity.
112
-
113
- *EkBass*, author of BazzBasic
114
-
115
- ---
116
-
117
- ## Case sensitivity
118
- BazzBasic is not case-sensitive except with string contents.
119
- ```basic
120
- let blaa$ = "Hello"
121
- PriNT BLAA$ ' output: Hello
122
- ```
123
 
124
  ---
125
 
126
  ## Line Continuation
127
 
128
- BazzBasic has **no line-continuation character**. Do not generate `_` (VBA), `\` (Python), or `&` (other dialects). The lexer figures out continuation automatically using two rules.
129
 
130
  **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:
131
 
@@ -144,8 +121,7 @@ LET counter$ +=
144
 
145
  Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
146
 
147
- > `%` IS a real binary modulo operator (`a % b`, same precedence as `*`/`/`, same result as `MOD(a, b)`) and DOES trigger continuation like the other arithmetic operators above.
148
- > `MOD` is a separate thing — a function `MOD(a, b)` — not a binary operator, so it does NOT trigger continuation (a `)` at line end never continues).
149
 
150
  **Rule 2 — open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
151
 
@@ -156,115 +132,90 @@ LET dist$ = DISTANCE(
156
  )
157
  ```
158
 
159
- Both rules combine:
160
-
161
- ```basic
162
- LET total$ = (
163
- base$ +
164
- tax$
165
- )
166
- ```
167
-
168
- **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.
169
-
170
  ---
171
 
172
  ## Variables & Constants
173
- Variables and constants must be declared with LET before they can be used.
174
- BazzBasic variables are not typed, but work the same way as in JavaScript, for example.
175
- A variable needs the suffix $ which often is linked as STRING in traditional basic variants.
176
 
177
- Variables require suffix "$". Constants require suffix "#".
178
- The suffix does not define data type — only "#" indicates immutability.
179
  ```basic
180
- LET a$ ' Declare variable without value
181
- LET b$, c$, d$ ' Multiple variable declarations without value
182
- LET e$, f$ = "foo", g$ = 10 ' Multiple variable declaration, e$ stays empty, f$ and g$ gets values
183
 
184
- LET name$ = "Alice" ' String variable
185
- LET score$ = 0 ' Numeric variable
186
 
187
- LET PI# = 3.14159 ' Constant (immutable)
188
- LET TITLE# = "My Game" ' String constant
189
  ```
190
 
191
- **Compound assignment operators** (variables only — **not** allowed with `#` constants):
192
 
193
  ```basic
194
  LET x$ = 1
195
- x$ += 5 ' add
196
- x$ -= 3 ' subtract
197
- x$ *= 2 ' multiply
198
- x$ /= 4 ' divide
199
  LET s$ = "Hello"
200
- s$ += " World" ' string concatenation
201
  ```
202
 
203
- **Scope:** All main-code variables share one scope (IF, FOR, and WHILE do NOT create new scope).
204
- Main-code variables ($) and arrays are NOT accessible inside DEF FN.
205
- `DEF FN` functions are fully isolated — only global constants (`#`) accessible inside.
206
 
207
  **Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
208
 
209
- ---
210
-
211
  ### Built-in Constants
212
- - **Boolean:** `TRUE` (`1`), `FALSE` (`0`) — plain numbers, not a separate type. `IF x$ = 1` and `IF x$ = TRUE` are identical.
213
- - **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e) — `#` suffix required
214
- - **System:** `PRG_ROOT#` (program base directory path)
215
- - **Version:** `BBVER#` (returns current version of BazzBasic, ie: "1.5")
216
- - **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_NUMPAD0#`…`KEY_NUMPAD9#`, `KEY_NUMPAD_PLUS#`/`_MINUS#`/`_MUL#`/`_DIV#`/`_DOT#`, `KEY_LSHIFT#`, `KEY_LCTRL#`, etc. — see *Keyboard Input*
217
- - **Gamepad:** buttons `PAD_A#`…`PAD_Y#`, `PAD_UP#`/`_DOWN#`/`_LEFT#`/`_RIGHT#`, `PAD_LB#`, `PAD_RB#`, `PAD_START#`, `PAD_BACK#` etc.; axes `PAD_LX#`, `PAD_LY#`, `PAD_RX#`, `PAD_RY#`, `PAD_LT#`, `PAD_RT#` — see *Gamepad*
218
 
219
  ---
220
 
221
  ## Arrays
222
- BazzBasic arrays are fully dynamic and support numeric, string, or mixed indexing.
223
 
 
224
 
225
  ```basic
226
  DIM scores$ ' Declare (required before use)
227
  DIM a$, b$, c$ ' Multiple
228
- scores$(0) = 95 ' Numeric indices are 0-based.
229
- scores$("name") = "Alice" ' String keys are associative, insertion-ordered.
230
  matrix$(0, 1) = "A2" ' Multi-dimensional
231
 
232
  DIM sounds$
233
- sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
234
- sounds$("guns", "shotgun_reload") = "reload_shotgun.wav"
235
- sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
236
- sounds$("guns", "ak47_reload") = "reload_ak47.wav"
237
- sounds$("food", "ham_eat") = "eat_ham.wav"
238
 
239
- PRINT LEN(sounds$()) ' 5 - total elements across both "guns" and "food" groups
240
- PRINT ROWCOUNT(sounds$()) ' 2, "guns" & "food"
241
 
242
  DIM car$
243
  car$("manufacturer") = "Ford"
244
  car$("engine") = "1.6 Eco"
245
- car$("color") = "Blue"
246
 
247
- FOR i$ = 0 TO LEN(car$()) - 1 ' Iterate an associative array: LEN + ARRKEY
248
- LET key$ = ARRKEY(car$(), i$) ' No FOREACH in BazzBasic - this is the idiom
249
  PRINT key$; " = "; car$(key$)
250
  NEXT i$
251
  ```
252
 
253
  | Function/Command | Description |
254
  |-----------------|-------------|
255
- | `LEN(arr$())` | Total element count (LEN counts all nested elements across all dimensions) |
256
  | `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
257
- | `ARRKEY(arr$(), i)` | Key at 0-based index `i`, in insertion order. Pair with `LEN` to loop over string-keyed arrays with `FOR/NEXT` or `WHILE/WEND`. Errors on out-of-range index. |
258
- | `HASKEY(arr$(key))` | 1 if exists, 0 if not |
259
  | `DELKEY arr$(key)` | Remove one element |
260
  | `DELARRAY arr$` | Remove entire array (can re-DIM after) |
261
- | `JOIN dest$, src1$, src2$` | Merge two arrays; `src2$` keys overwrite `src1$`. Use empty `src1$` as `COPYARRAY`. |
262
-
263
- **JOIN** Matching keys from src2$ overwrite src1$ at the same level
264
-
265
- **Always check with `HASKEY` before reading uninitialized elements.**
266
 
267
- > `DIM arr$ = value` (single value, not `key=value` text) stores it at `arr$(0)` — NOT as a scalar. `DIM x$ = 5` does not make `x$` printable as a plain number; it makes `x$(0)` equal `5`. If a scalar is what you want, use `LET`, not `DIM`.
268
 
269
  ---
270
 
@@ -296,8 +247,7 @@ WEND
296
  ' Labels, GOTO, GOSUB
297
  [start]
298
  GOSUB [sub:init]
299
- ' Avoid jumping into the middle of logical blocks (e.g. inside IF/WHILE)
300
- GOTO [start]
301
 
302
  [sub:init]
303
  LET x$ = 0
@@ -307,77 +257,59 @@ RETURN
307
  LET target$ = "[menu]"
308
  GOTO target$
309
 
310
- ' Other
311
  SLEEP 2000 ' Pause for milliseconds
312
  END ' Terminate program
313
  ```
314
- **Note:** Labels are case-insensitive and may contain almost any printable character.
315
- Whitespace is trimmed. Everything between "[" and "]" is treated as the label name.
 
316
  ---
317
 
318
  ## I/O
319
 
320
  | Command | Description |
321
  |---------|-------------|
322
- | `PRINT expr; expr` | `;` = no space, `,` = tab |
323
  | `PRINT "text";` | Trailing `;` suppresses newline |
324
- | `INPUT "prompt", var$` | Splits on whitespace/comma |
325
  | `INPUT "prompt", a$, b$` | Multiple values |
326
  | `LINE INPUT "prompt", var$` | Read entire line with spaces |
327
- | `CLS` | Clear screen |
328
  | `LOCATE row, col` | Move cursor (1-based) |
329
  | `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
330
  | `CURPOS()` | Read cursor as `"row,col"` string |
331
- | `COLOR fg, bg` | Text colors (0–15 palette) |
 
332
  | `SHELL("cmd")` | Run shell command, returns output |
333
  | `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
334
 
335
- ' ; prints without spacing
336
- ' , prints tab separation
337
- ' Both can be mixed in a single PRINT statement
338
- ' INPUT splits on whitespace and comma; quoted strings are treated as single values
339
 
340
- **Escape sequences in strings:** `\"` `\n` `\t` `\\`
341
-
342
- **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:
343
- - Always append `2>&1` to the command, or SQL errors disappear silently.
344
- - Use `\"` (BazzBasic escape) to wrap the SQL for the OS shell: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
345
  - In paths use `/` or `\\` — never a single `\`.
346
 
347
  ### Keyboard Input
348
  | Function | Returns | Notes |
349
  |----------|---------|-------|
350
  | `INKEY` | Key value or 0 | Non-blocking |
351
- | `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection; KEYDOWN only works in graphics mode |
352
  | `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
353
 
354
- **Keyboard layouts.** Letters (`KEY_A#`…`KEY_Z#`), digits, arrows, Space/Enter/Esc, F-keys,
355
- numpad and modifiers are the same on every keyboard layout — use these for controls.
356
- Main-keyboard punctuation (`+ - = , . /` etc. and their `KEY_*#` constants) depends on the
357
- layout: never bind controls to `ASC("+")` or `ASC("-")`. Use letters or
358
- `KEY_NUMPAD_PLUS#` / `KEY_NUMPAD_MINUS#` instead.
359
-
360
  - Letters always return uppercase codes (`"a"` and `"A"` → `KEY_A#`), in both graphics and console mode.
361
- - `KEYDOWN` follows the key *label* on the current layout, same as `INKEY`: `KEYDOWN(KEY_A#)` is the key that types "a" (on AZERTY that is a different physical key than on QWERTY). If no key types a punctuation character without modifiers (e.g. "=" on a Finnish keyboard), `KEYDOWN` of that constant is always FALSE.
362
- - Numpad: `KEY_NUMPAD0#`…`KEY_NUMPAD9#`, `KEY_NUMPAD_PLUS#`, `KEY_NUMPAD_MINUS#`,
363
- `KEY_NUMPAD_MUL#`, `KEY_NUMPAD_DIV#`, `KEY_NUMPAD_DOT#` (graphics mode). Numpad Enter = `KEY_ENTER#`.
364
- - INKEY consumes the key: read it once per loop pass into a variable (`LET k$ = INKEY`)
365
- and compare the variable. Two `INKEY` calls in one pass → the second returns 0.
366
- - Console mode: INKEY/WAITKEY return the typed character (except letters and special keys);
367
- numpad returns the typed digit, not `KEY_NUMPAD*#`. KEYDOWN is graphics-only.
368
-
369
  ### Mouse (graphics mode only)
370
  `MOUSEX`, `MOUSEY` — cursor position
371
- `MOUSELEFT`, MOUSERIGHT, MOUSEMIDDLE — return 1 if pressed, 0 otherwise
372
- `MOUSEHIDE` — hide the mouse cursor (graphics screen only)
373
- `MOUSESHOW` — restore the mouse cursor (graphics screen only)
374
-
375
- ### Gamepad (console AND graphics mode) — added in v1.5
376
-
377
- > **DISCLAIMER:** BazzBasic version 1.5 has been tested with only one PS4-compatible Bluetooth controller. Therefore, for the time being, I cannot guarantee that GamePad support will work with all different types of controllers.
378
-
379
- When a user reports a pad not being detected, wrong button mapping or odd axis values, keep this in mind: it may be an untested-controller issue rather than a bug in their code.
380
 
 
381
  | Function | Returns | Notes |
382
  |----------|---------|-------|
383
  | `GAMEPADS()` | Number of connected pads | Parentheses optional |
@@ -386,57 +318,48 @@ When a user reports a pad not being detected, wrong button mapping or odd axis v
386
  | `PADNAME(pad)` | String | e.g. `"PS4 Controller"`, `""` if not connected |
387
  | `PADRUMBLE pad, strength, ms` | — (statement) | strength 0.0…1.0, non-blocking, parentheses optional |
388
 
389
- - Pad index is **0-based**, max 8 pads. A pad keeps its number while connected (stable slots, not re-packed on disconnect).
390
- - **No `SCREEN` needed** — unlike `KEYDOWN`/mouse, gamepad functions work in console programs too.
391
- - **Disconnected pad = no input, never an error:** `PADBUTTON` → FALSE, `PADAXIS` → 0, `PADNAME` → `""`. Do not generate guard code like `IF GAMEPADS() > 0 THEN` around every read; use `GAMEPADS()` only to show a "connect a pad" message.
392
- - Hot-plug works: pads connected while the program runs are picked up automatically.
393
- - Button constants (Xbox naming): `PAD_A#` `PAD_B#` `PAD_X#` `PAD_Y#`, `PAD_UP#` `PAD_DOWN#` `PAD_LEFT#` `PAD_RIGHT#`, `PAD_LB#` `PAD_RB#`, `PAD_LSTICK#` `PAD_RSTICK#`, `PAD_BACK#` `PAD_START#` `PAD_GUIDE#`, `PAD_MISC#`, `PAD_TOUCHPAD#`. PlayStation: A=Cross, B=Circle, X=Square, Y=Triangle. Raw numbers 0–20 are valid (16–19 = Elite paddles); outside that → error.
394
- - Axis constants: `PAD_LX#` `PAD_LY#` `PAD_RX#` `PAD_RY#` `PAD_LT#` `PAD_RT#`. Raw 0–5; outside → error.
395
- - **Y axis: negative = up**, same direction as screen Y. So `y$ = y$ + PADAXIS(0, PAD_LY#) * SPEED#` moves correctly — do not invert it.
396
- - **L2/R2 are triggers, not buttons.** Read them with `PADAXIS(pad, PAD_LT#)` / `PADAXIS(pad, PAD_RT#)`. Never pass an axis constant to `PADBUTTON`: constants are plain numbers, so `PADBUTTON(0, PAD_LT#)` silently reads button 4 (= `PAD_BACK#`) with no error.
397
- - `PADBUTTON` is TRUE every frame while held. For one action per press, keep the previous state: `IF now$ AND NOT was$ THEN ...` then `was$ = now$`.
398
  - Stick as digital direction: `IF PADAXIS(0, PAD_LX#) < -0.5 THEN ...`
399
- - Typical game input = pad OR keyboard: `IF PADBUTTON(0, PAD_LEFT#) OR KEYDOWN(KEY_LEFT#) THEN dx$ = -1`
400
- - Many third-party pads identify as PS4/Xbox controllers — normal, mapping still correct.
401
-
402
- ### Console Read
403
- Returns numeric or character depending on type parameter
404
- `GETCONSOLE(row, col, type)` — type: 0=char (ASCII), 1=fg color, 2=bg color
405
 
406
  ---
407
 
408
  ## User-Defined Functions
409
 
410
  ```basic
411
- ' Define BEFORE calling. Name must end with $.
412
  DEF FN Clamp$(val$, lo$, hi$)
413
  IF val$ < lo$ THEN RETURN lo$
414
  IF val$ > hi$ THEN RETURN hi$
415
  RETURN val$
416
  END DEF
417
 
418
- PRINT FN Clamp$(5, 1, 10) ' ✓ OK — return value used
419
- LET v$ = FN Clamp$(15, 0, 10) ' ✓ OK
420
  FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
421
  ```
422
 
423
- - Isolated scope: no access to global `$` variables or global arrays, only global constants (`#`). Using a global array inside a function is an error: `Global array G$ is not visible inside DEF FN - pass it as a parameter with ASJSON() and rebuild it with ASARRAY()`
424
- - **Arrays inside functions:** `DIM` inside a function always creates a **fresh, empty, local** array on every call (and on every recursion level). Local arrays do not survive between calls:
425
- ```basic
426
  DEF FN Count$(x$)
427
- DIM t$ ' new empty array on every call
428
  t$(x$) = 1
429
  RETURN LEN(t$())
430
  END DEF
431
  PRINT FN Count$(1) ' 1
432
  PRINT FN Count$(2) ' 1 (not 2)
433
- ```
434
- (In v1.4c and older, arrays `DIM`'d in a function kept their contents between calls, and functions could accidentally reach global arrays by name. Both are fixed in the current source.)
435
- - Parameters passed **by value**
436
  - Labels inside functions are local — GOTO/GOSUB cannot jump outside
437
- - Supports recursion — uses the real call stack, so extremely deep recursion (thousands of levels) can overflow it. GOSUB/RETURN uses a separate, heap-based stack with no such limit.
438
- - Arrays as parameters not allowed. Use ASJSON to make array as JSON-string to pass it.
439
- - Use `INCLUDE` to load functions from separate files if many
440
 
441
  ---
442
 
@@ -446,9 +369,8 @@ FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
446
  |----------|-------------|
447
  | `ASC(s$)` | ASCII code of first char |
448
  | `CHR(n)` | Character from ASCII code |
449
- | `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive by default |
450
  | `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
451
- | `INSTR(start, s$, search$)` | Search from position (case-sensitive) |
452
  | `INVERT(s$)` | Reverse string |
453
  | `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
454
  | `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars |
@@ -458,24 +380,18 @@ FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
458
  | `MID(s$, start, len)` | Substring with length |
459
  | `REPEAT(s$, n)` | Repeat string n times |
460
  | `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
461
- | `SPLIT(arr$, s$, sep$)` | Split into array (keys `0`..`count-1`), returns count. The array is emptied first, so re-splitting a shorter string leaves no old elements. `arr$()` also accepted as first argument |
462
- | `SRAND(n)` | Random alphanumeric string of length n |
463
  | `STR(n)` | Number to string |
464
  | `VAL(s$)` | String to number |
465
  | `SHA256(s$)` | SHA256 hash (64-char hex) |
466
  | `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
467
 
468
- > `SRAND(n)` with `n < 0` throws an unhandled arithmetic error (`n = 0` is safe, returns `""`). Never pass an unvalidated or negative length.
469
- > ```basic
470
- > PRINT SRAND(-1)
471
- > ' Error: Arithmetic operation resulted in an overflow.
472
- > ```
473
-
474
  ---
475
 
476
  ## FSTRING — String Interpolation
477
 
478
- `FSTRING(template$)` substitutes `{{-name-}}` placeholders inside a template string with the value of variables, constants, or array elements. Preferred over long `+` concatenation chains.
479
 
480
  ```basic
481
  LET name$ = "Krisu"
@@ -484,39 +400,28 @@ PRINT FSTRING("Hello {{-name$-}}, level {{-LEVEL#-}}")
484
  ' Output: Hello Krisu, level 5
485
  ```
486
 
487
- The triple-character markers `{{-` and `-}}` are deliberately unusual so they will not collide with normal text. There is no escape syntax — literal `{{-...-}}` in the template is always parsed as a placeholder.
488
-
489
- ### Placeholder forms
490
 
491
  | Form | Resolves to |
492
  |------|-------------|
493
- | `{{-var$-}}` | Value of variable `var$` |
494
- | `{{-CONST#-}}` | Value of constant `CONST#` |
495
- | `{{-arr$(0)-}}` | Array element at numeric index `0` |
496
- | `{{-arr$(i$)-}}` | Array element at index taken from variable `i$` |
497
- | `{{-arr$(KEY#)-}}` | Array element at index taken from constant `KEY#` |
498
- | `{{-arr$(name)-}}` | Array element at literal string key `"name"` (no quotes inside FSTRING) |
499
- | `{{-arr$(0, i$)-}}` | Multidimensional element, mixed literal and variable indices |
500
-
501
- ### Index resolution rule (array access)
502
-
503
- For each comma-separated index, FSTRING looks at the last character:
504
-
505
  1. Ends with `$` or `#` → variable / constant lookup. Halts if undefined.
506
- 2. Parses as a number (`0`, `1.5`, `-3`) → numeric index. `arr$(01)` and `arr$(1.0)` both resolve to key `1`.
507
- 3. Otherwise → literal string key. This is what lets `{{-player$(name)-}}` read what was stored with `player$("name") = ...`.
508
 
509
- ### Notes
510
 
511
- - Whitespace inside placeholders is trimmed: `{{- name$ -}}` ≡ `{{-name$-}}`.
512
- - Built-in constants work too (`{{-PI#-}}`, `{{-EULER#-}}`, `{{-arr$(KEY_A#)-}}`) — checked before user variables, same order as normal expressions. (In v1.4c they failed with "undefined variable".)
513
- - Numbers auto-stringify — no `STR()` needed for numeric variables, constants, or array elements.
514
- - FSTRING returns a value; you must use it (`LET`, `PRINT`, pass to function). Calling it as a bare statement is an error.
515
- - Errors halt the program with a line-numbered message: undefined variable, missing closing `-}}`, empty placeholder `{{--}}`, malformed array access, uninitialized array element.
516
 
517
- ### Not supported (intentional)
518
-
519
- No arithmetic, function calls, nested lookups, or quoted string literals inside placeholders. Pre-compute into a variable and reference that:
520
 
521
  ```basic
522
  ' ❌ WRONG
@@ -531,19 +436,7 @@ LET k$ = arr2$(0)
531
  PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
532
  ```
533
 
534
- ### Common AI mistakes with FSTRING
535
-
536
- ```basic
537
- ' ❌ WRONG ' ✓ CORRECT
538
- FSTRING("Hi {{name$}}") FSTRING("Hi {{-name$-}}")
539
- FSTRING("Hi {-name$-}") FSTRING("Hi {{-name$-}}")
540
- FSTRING("Hi {{-name-}}") ' array key FSTRING("Hi {{-name$-}}")
541
- FSTRING("Hi {{-name$-}}") ' as stmt LET s$ = FSTRING("Hi {{-name$-}}")
542
- ```
543
-
544
- Inside a placeholder, `name` (no suffix) is treated as a literal string key for an array lookup, **not** as a reference to variable `name$`. Always include the suffix.
545
-
546
- ### Full working example
547
 
548
  ```basic
549
  DIM player$
@@ -552,25 +445,17 @@ DIM player$
552
  player$("level") = 99
553
 
554
  DIM grid$
555
- grid$(0, 0) = "X"
556
- grid$(0, 1) = "O"
557
  grid$(1, 0) = "."
558
  grid$(1, 1) = "X"
559
 
560
  LET row$ = 1
561
- LET PI# = 3.14
562
 
563
  PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
564
  PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
565
- PRINT FSTRING("Pi is roughly {{-PI#-}}")
566
  END
567
- ```
568
-
569
- Output:
570
- ```
571
- Krisu the Bass, lvl 99
572
- Row 1: [.X]
573
- Pi is roughly 3.14
574
  ```
575
 
576
  ---
@@ -581,9 +466,9 @@ Pi is roughly 3.14
581
  |----------|-------------|
582
  | `ABS(n)` | Absolute value |
583
  | `ATAN(n)` | Arc tangent |
584
- | `ATAN2(n, n2)` | 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 |
585
  | `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
586
- | `INBETWEEN(n, min, max)` | TRUE if min < n < max (strictly between, not equal) |
587
  | `CEIL(n)` / `FLOOR(n)` | Round up / down |
588
  | `CINT(n)` | Round to nearest integer |
589
  | `CLAMP(n, min, max)` | Constrain n to [min, max] |
@@ -596,47 +481,39 @@ Pi is roughly 3.14
596
  | `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
597
  | `LOG(n)` | Natural logarithm |
598
  | `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
599
- | `MOD(a, b)` | Remainder |
600
- | `a % b` | Same as `MOD(a, b)` — binary modulo operator form |
601
  | `POW(base, exp)` | Power |
602
- | `RND(n)` | Random integer 0 to n-1 if n > 0 |
603
- | `RND(0)` | Float between 0.0 and 1.0 (IE: 0.5841907423666761) |
604
- | `ROUND(n)` | Rounds to nearest integer, half rounds away from zero (`0.5→1`, `-0.5→-1`) — NOT banker's rounding |
605
  | `SGN(n)` | Sign: -1, 0, or 1 |
606
  | `SQR(n)` | Square root |
607
 
608
- **Math constants:** `PI#`, `HPI#` (PI/2), `QPI#` (PI/4), `TAU#` (PI*2), `EULER#`
 
 
 
 
 
 
 
 
 
 
609
 
610
  ---
611
 
612
- ## Variable Functions
613
 
614
- | Function | Description |
615
- |----------|-------------|
616
- | `ISSET(name)` | `1` if the named variable (`$`) or constant (`#`) is declared, `0` otherwise. Argument is **not evaluated** — `ISSET(undef$)` safely returns `0`. |
617
-
618
- `ISSET` is the only language-introspection function and it has tight rules:
619
-
620
- - **Scalars only.** Variables (`$`) and constants (`#`). Arrays and array elements are stored separately — `ISSET(arr$)` and `ISSET(arr$(0))` always return `0`, never an error.
621
- - **Bare name only.** No expressions, no string literals, no numbers. These all error with "invalid parameter":
622
- ```basic
623
- ISSET(a$ + b$) ' WRONG: expression
624
- ISSET("a$") ' WRONG: string literal
625
- ISSET(42) ' WRONG: number
626
- ISSET() ' WRONG: empty
627
- ```
628
- - **Suffix is part of the name.** `a$` and `A#` are different names:
629
- ```basic
630
- LET a$ = "foo"
631
- PRINT ISSET(a$) ' 1
632
- PRINT ISSET(A#) ' 0
633
- ```
634
- - **`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".
635
-
636
- Typical use is guarding optional setup:
637
 
638
  ```basic
639
- IF NOT ISSET(playerName$) THEN
640
  LET playerName$ = "Anonymous"
641
  END IF
642
  ```
@@ -653,63 +530,45 @@ FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
653
  FULLSCREEN FALSE ' Windowed
654
  ```
655
 
656
- | Mode | Resolution |
657
- |------|-----------|
658
- | 1 | 320×200 |
659
- | 2 | 640×350 |
660
- | 7 | 320×200 |
661
- | 9 | 640×350 |
662
- | 12 | 640×480 ← recommended |
663
- | 13 | 320×200 |
664
 
665
  ### Drawing Primitives
666
  ```basic
667
- PSET (x, y), color ' Pixel
668
- LINE (x1,y1)-(x2,y2), color ' Line
669
- LINE (x1,y1)-(x2,y2), color, B ' Box outline
670
- LINE (x1,y1)-(x2,y2), color, BF ' Box filled (FAST — use instead of CLS)
671
- CIRCLE (cx,cy), radius, color ' Circle outline
672
- CIRCLE (cx,cy), radius, color, 1 ' Circle filled
673
- PAINT (x, y), fillColor, borderColor ' Flood fill
674
- LET c$ = POINT(x, y) ' Read pixel color
675
- LET col$ = RGB(r, g, b) ' Create color (0–255 each)
676
  ```
677
 
678
- **Color values:** Every drawing primitive (`PSET`, `LINE`, `CIRCLE`, `PAINT`, `DRAWSTRING`, `LOADSHAPE`) accepts a `color` parameter that is either a palette index 0–15 or an `RGB(r, g, b)` value — mix freely. The `COLOR` text command is the exception: it accepts palette indices 0–15 only, so `COLOR RGB(...)` does **not** work.
679
 
680
  **Palette (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
681
 
682
- > Do **not** hand-construct packed RGB integers (e.g. `16711680`). `RGB()` tags its return value internally so it can be told apart from a palette index; a raw integer lacks that tag and will be misread as a palette index. Always use `RGB(r, g, b)`.
683
-
684
  ### Screen Control
685
  ```basic
686
- SCREENLOCK ON ' Buffer drawing (start frame)
687
- SCREENLOCK OFF ' Present buffer (end frame)
688
- VSYNC(TRUE) ' Enable VSync (default, ~60 FPS)
689
  VSYNC(FALSE) ' Disable VSync (benchmarking)
690
- CLS ' Clear screen
691
- ' Use CLS only with console, in graphics screen its slow
692
- ' With graphics screen, prefer LINE BF
693
  ```
694
 
695
  ### Shapes & Images
696
  ```basic
697
- ' Create shape
698
- ' LOADSHAPE and LOADIMAGE return a stable integer handle — never reassigned.
699
- ' SDL2 owns the resource; your code only ever holds this one reference. Use constants.
700
- LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
701
  LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
702
- LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
703
 
704
  ' Sprite sheet — sprites indexed 0-based
705
  DIM sprites$
706
- LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
707
- MOVESHAPE sprites$(0), x, y ' sprites$(0) = first sprite
708
 
709
- ' Transform
710
- ' NOTE: anchor point differs by type — LOADSHAPE primitives (RECTANGLE/CIRCLE/TRIANGLE)
711
- ' are center-anchored; LOADIMAGE images are top-left-anchored.
712
- MOVESHAPE RECT#, x, y ' Position by center point (LOADSHAPE shape)
713
  ROTATESHAPE RECT#, angle ' Degrees (absolute)
714
  SCALESHAPE RECT#, scale ' 1.0 = original size
715
  DRAWSHAPE RECT# ' Render to buffer
@@ -717,39 +576,28 @@ SHOWSHAPE RECT# / HIDESHAPE RECT# ' Toggle visibility
717
  REMOVESHAPE RECT# ' Free memory (always clean up)
718
  ```
719
 
 
720
 
721
- ---
722
-
723
- ### Text Rendering (SDL2_ttf.dll required)
724
- #### DRAWSTRING & LOADFONT
725
-
726
 
727
  ```basic
728
- ' Default font: Arial, 16px
729
- DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
730
-
731
- ' Load alternative font — becomes the new default
732
- LOADFONT "comic.ttf", 24
733
- DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
734
-
735
- ' Reset to Arial, 16px
736
- LOADFONT
737
  ```
738
 
739
- `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. Default font size is **16px** — not 20px.
740
 
741
  ---
742
 
743
  ## Sound
744
 
745
  ```basic
746
- ' LOADSOUND returns a stable integer handle — SDL2 manages the resource.
747
- ' The handle never changes; store it in a constant to protect it from accidental reassignment.
748
  LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
749
  SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
750
- SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
751
- SOUNDREPEAT(SND_JUMP#) ' Loop continuously
752
- SOUNDSTOP(SND_JUMP#) ' Stop specific sound
753
  SOUNDSTOPALL ' Stop all sounds
754
  ```
755
 
@@ -760,32 +608,27 @@ Load all sounds at startup. Call `SOUNDSTOPALL` before `END`.
760
  ## File I/O
761
 
762
  ```basic
763
- LET data$ = FileRead("file.txt") ' Read as string
764
- DIM cfg$ : LET cfg$ = FileRead("settings.txt") ' Read as key=value array
765
- FILEWRITE "save.txt", data$ ' Create/overwrite
766
- FILEAPPEND "log.txt", entry$ ' Append
767
- LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
768
- FILEDELETE "temp.dat" ' Delete file
769
  DIM files$
770
- LET n$ = FILELIST(files$, "levels", "*.txt") ' File names into files$(0..n-1), returns n
771
  ```
772
 
773
- **FILELIST:** `FILELIST(arr$, folder$ [, pattern$])` lists files only (no folders, not recursive), names only (no paths), sorted alphabetically ignoring case. The array is cleared first. `pattern$` supports `*` and `?`, default all files. Hidden/system files are skipped. Missing folder → returns `0`. To open a listed file, prepend the folder: `FILEREAD("levels/" + files$(i$))`. Added after v1.4c.
774
-
775
- **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.
776
 
777
  ```basic
778
  DIM env$
779
- LET env$ = FileRead(".env")
780
  LET API_KEY# = env$("OPENAI_API_KEY")
781
  ```
782
 
783
- **Paths:** Use `/` or `\\` — never single `\` (it's an escape char). Relative paths are from `PRG_ROOT#`.
784
- `PRG_ROOT#` already ends with a directory separator — concatenate directly, don't add your own `/`:
785
- ```basic
786
- LET path$ = PRG_ROOT# + "data.txt"
787
- ```
788
- **FileWrite with array** saves in key=value format (round-trips with FileRead).
789
 
790
  ---
791
 
@@ -795,41 +638,35 @@ LET path$ = PRG_ROOT# + "data.txt"
795
  LET res$ = HTTPGET("https://api.example.com/data")
796
  LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
797
 
798
- ' With headers (optional)
799
  DIM headers$
800
  headers$("Authorization") = "Bearer mytoken"
801
  headers$("Content-Type") = "application/json"
802
  LET res$ = HTTPGET("https://api.example.com/data", headers$)
803
  LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
804
 
805
- ' With timeout in seconds (optional, comes AFTER headers; default 30, 0 = no limit)
806
- LET res$ = HTTPGET("https://api.example.com/data", headers$, 60)
807
  LET res$ = HTTPPOST("http://localhost:11434/v1/chat/completions", body$, headers$, 120)
808
  ```
809
 
810
  ### Local HTTP server (LISTEN)
811
 
812
- 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.
813
 
814
  ```basic
815
- STARTLISTEN 8080 ' bind 127.0.0.1:8080, no admin needed
816
- STARTLISTEN 8080, 5000 ' optional timeout in ms
817
- LET body$ = GETREQUEST() ' POST/PUT/PATCH body, or GET query string ("" on timeout)
818
- SENDRESPONSE "{""status"":""ok""}" ' must be called or browser hangs
819
  STOPLISTEN
820
  ```
821
 
822
- Important rules:
823
-
824
- - **Always pair `GETREQUEST()` with `SENDRESPONSE`.** The browser is waiting on the response. Forgetting `SENDRESPONSE` makes the page hang.
825
- - **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.
826
- - **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$)`.
827
- - **OPTIONS preflight is automatic.** Do NOT write code that handles `OPTIONS` — it is consumed silently and never reaches user code.
828
- - **CORS is automatic.** Every response carries `Access-Control-Allow-Origin: *`. No need to set it manually.
829
- - **One listener at a time.** Calling `STARTLISTEN` while one is already active is an error. Call `STOPLISTEN` first.
830
- - **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.
831
-
832
- Typical receive-and-process pattern:
833
 
834
  ```basic
835
  STARTLISTEN 8080
@@ -837,8 +674,7 @@ PRINT "Waiting for browser..."
837
 
838
  LET json$ = GETREQUEST()
839
  DIM data$
840
- LET data$ = ASARRAY(json$)
841
-
842
  PRINT "Got name: " + data$("name")
843
 
844
  SENDRESPONSE "{""status"":""ok""}"
@@ -850,66 +686,70 @@ END
850
 
851
  ## Arrays & JSON
852
 
853
- Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`
854
 
855
  ```basic
856
- ' Array → JSON string
857
- LET json$ = ASJSON(arr$)
858
-
859
- ' JSON string → array (returns element count)
860
  DIM data$
861
- LET count$ = ASARRAY(data$, json$)
862
-
863
- ' Load/save JSON files
864
- LOADJSON arr$, "file.json"
865
- SAVEJSON arr$, "file.json"
866
  ```
867
 
868
- ---
869
-
870
- ## Fast Trigonometry
871
 
872
- ~20× faster than `SIN(RAD(x))`, 1-degree precision. Uses ~5.6 KB memory.
873
 
874
  ```basic
875
- FastTrig(TRUE) ' Enable lookup tables (must call first)
876
- LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
877
- LET y$ = FastSin(90)
878
- LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
879
- FastTrig(FALSE) ' Free memory
880
- ```
 
 
 
 
 
881
 
882
- Use for raycasting, sprite rotation, particle systems, any high-freq trig.
 
 
 
 
883
 
884
  ---
885
 
886
  ## Date & Time
887
 
888
  ```basic
889
- LET t$ = TIME() ' Current time, default format "HH:mm:ss" -> "15:21:22"
890
- LET t2$ = TIME("dd.MM.yyyy") ' .NET DateTime format string -> "04.09.2026"
891
  LET t3$ = TIME("dddd") ' -> "Friday"
892
-
893
  LET start$ = TICKS ' Milliseconds since program start
894
- ' ... later in a loop ...
895
- LET elapsed$ = TICKS - start$ ' Delta time — use for frame-independent movement
896
  ```
897
 
898
- `TICKS` is the standard way to do frame-independent (delta-time) movement in a game loop — prefer it over counting fixed `SLEEP` increments.
 
 
 
899
 
900
  ```basic
901
- ' ✅ Preferred: frame-independent movement
902
- LET lastTick$ = TICKS
903
- WHILE running$
904
- LET delta$ = TICKS - lastTick$
905
- lastTick$ = TICKS
906
- x$ = x$ + speed$ * delta$ / 16 ' normalize to ~60 FPS baseline
907
- GOSUB [sub:draw]
908
- WEND
909
 
910
- ' ❌ Avoid: fixed SLEEP without delta — speed varies with actual frame rate
911
- SLEEP 16
912
- x$ = x$ + speed$
 
 
 
 
 
913
  ```
914
 
915
  ---
@@ -918,12 +758,12 @@ x$ = x$ + speed$
918
 
919
  ```basic
920
  ' bazzbasic.exe myprog.bas arg1 arg2
921
- PRINT ARGCOUNT ' number of args (2 in this example)
922
- PRINT ARGS(0) ' first arg → "arg1"
923
- PRINT ARGS(1) ' second arg → "arg2"
924
  ```
925
 
926
- `ARGCOUNT` and `ARGS(n)` are 0-based; ARGS does not include the interpreter or script name.
927
 
928
  ---
929
 
@@ -939,60 +779,30 @@ INCLUDE "MathLib.bb" ' Load compiled library
939
  PRINT FN MATHLIB_add$(5, 3)
940
  ```
941
 
942
- Library functions can read main-program constants (`#`). `.bb` files are version-locked.
943
-
944
- - **No extension fallback.** `INCLUDE "helpers"` does NOT try `helpers.bas` automatically — give the exact filename, extension included.
945
- - **Path resolution order:** relative to the *including file's own directory* first, then relative to the program's base path.
946
- - **Circular includes are detected** and halt with `Circular INCLUDE detected: <file>`.
947
-
948
- ---
949
-
950
- ## Passing Arrays to Functions
951
-
952
- 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+.
953
-
954
- ```basic
955
- DEF FN ProcessPlayer$(data$)
956
- DIM arr$
957
- LET count$ = ASARRAY(arr$, data$)
958
- RETURN arr$("name") + " score:" + arr$("score")
959
- END DEF
960
-
961
- [inits]
962
- DIM player$
963
- player$("name") = "Alice"
964
- player$("score") = 9999
965
- player$("address,city") = "New York"
966
-
967
- [main]
968
- LET json$ = ASJSON(player$)
969
- PRINT FN ProcessPlayer$(json$)
970
- END
971
- ```
972
-
973
- **Notes:**
974
- - The function receives a full independent copy — changes inside do not affect the original array
975
- - Nested keys work normally: `arr$("address,city")` etc.
976
- - Overhead is similar to copying an array manually; acceptable for most use cases
977
 
978
  ---
979
 
980
  ## Program Structure
981
 
982
  ```basic
983
- ' ---- 1. FUNCTIONS (or INCLUDE "functions.bas/bb") ----
984
  DEF FN Clamp$(v$, lo$, hi$)
985
  IF v$ < lo$ THEN RETURN lo$
986
  IF v$ > hi$ THEN RETURN hi$
987
  RETURN v$
988
  END DEF
989
 
990
- ' ---- 2. INIT (declare ALL constants & variables here, not inside loops) ----
991
- ' Performance: variables declared outside loops avoid repeated existence checks.
992
  [inits]
993
- LET SCREEN_W# = 640
994
- LET SCREEN_H# = 480
995
- LET MAX_SPEED# = 5
 
996
 
997
  SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
998
 
@@ -1005,13 +815,12 @@ END DEF
1005
  WHILE running$
1006
  IF INKEY = KEY_ESC# THEN running$ = FALSE
1007
  GOSUB [sub:update]
1008
- GOSUB [sub:draw]
1009
- SLEEP 16
1010
  WEND
1011
  SOUNDSTOPALL
1012
- END ' place at the end of main program so BazzBasic wont fall to subs in runtime
1013
 
1014
- ' ---- 4. SUBROUTINES (or INCLUDE "subs.bas") ----
1015
  [sub:update]
1016
  IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
1017
  IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
@@ -1020,81 +829,37 @@ RETURN
1020
  [sub:draw]
1021
  SCREENLOCK ON
1022
  LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
1023
- CIRCLE (x$, y$), 10, RGB(0, 255, 0), 1
1024
  SCREENLOCK OFF
1025
  RETURN
1026
  ```
1027
 
1028
- **Key conventions:**
1029
- - Variables: `camelCase$` | Constants: `UPPER_SNAKE_CASE#` | Functions: `PascalCase$`
1030
- - Labels: `[gameLoop]` for jump targets, `[sub:name]` for subroutines
1031
- - Image/sound/shape IDs are stable integer handles — **always** store as constants: `LET MY_IMG# = LOADIMAGE("x.png")` — never use `$` variables for these
1032
- - Group many IDs → use arrays: `DIM sprites$` / `sprites$("player") = LOADIMAGE(...)` — but prefer named constants when count is small
1033
-
1034
- ---
1035
-
1036
- ## Performance Tips
1037
-
1038
- - `LINE (0,0)-(W,H), 0, BF` to clear — much faster than `CLS`
1039
- - Always wrap draw code in `SCREENLOCK ON` / `SCREENLOCK OFF`
1040
- - Store `RGB()` results in constants/variables — don't call RGB in hot loops
1041
- - Declare all variables in `[inits]`, not inside loops or subroutines
1042
- - Use `FastTrig` for any loop calling trig hundreds of times per frame
1043
- - `SLEEP 16` in game loop → ~60 FPS
1044
 
1045
  ---
1046
 
1047
- ## Known Limitations
1048
-
1049
- Things to be aware of — most are deliberate design decisions, a few are practical constraints.
1050
-
1051
- - **No line numbers.** Never supported, never will be.
1052
- - **Platform: Windows x64 only.** Linux and macOS are not supported. Browser/Android are not feasible — the runtime depends on SDL2 via P/Invoke.
1053
- - **Arrays cannot be passed to functions.** Use the `ASJSON` / `ASARRAY` round-trip pattern. The function receives an independent copy.
1054
- - **`DEF FN` scope is fully isolated.** Functions can read global `#` constants but cannot see any `$` variables or arrays from the outer scope. Pass values as parameters, arrays as `ASJSON()` strings.
1055
- - **No block scope.** `IF`, `FOR`, and `WHILE` do not create new variable scopes — all main-code variables share one namespace.
1056
- - **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.
1057
- - **Division by zero returns `0` silently.** No exception, no warning. Guard with `IF b$ = 0 THEN ...` when correctness matters.
1058
- - **No integer-division operator.** Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` depending on the rounding behavior you need.
1059
- - **Compiled `.bb` libraries are version-locked** to the BazzBasic build that produced them. Recompile after upgrading the interpreter.
1060
- - **`DEF FN` definitions must precede their first call** in source order. Forward references don't resolve.
1061
 
1062
- ---
1063
-
1064
- ## IDE Features
1065
 
1066
- ### Menus
1067
  | Menu | Items |
1068
  |------|-------|
1069
- | **File** | New (Ctrl+N), Open (Ctrl+O), Save (Ctrl+S), Save As (Ctrl+Shift+S), Close Tab (Ctrl+W), Exit (Alt+F4) |
1070
- | **Edit** | Undo (Ctrl+Z), Redo (Ctrl+Y), Cut (Ctrl+X), Copy (Ctrl+C), Paste (Ctrl+V), Select All (Ctrl+A) |
1071
- | **Search** | Find (Ctrl+F), Replace (Ctrl+H) |
1072
- | **View** | Light Mode, Dark Mode (experimental; choice saved to `%AppData%\BazzBasic\ide.json`) |
1073
- | **Run** | Run Program (F5), Compile as Exe, Compile as Library (.bb) |
1074
- | **Help** | About, Online Manual, Beginner's Guide, Rosetta Code, Check for Updates |
1075
-
1076
- **Version note:** In v1.4c and older, Find and Replace are under **Edit**, there is no Undo/Redo/Cut/Copy/Paste menu (the shortcuts still work in the editor), there is no View menu or Dark Mode, and Help has no Online Manual or Rosetta Code links. If a user says Find is under Edit, they have an older build.
1077
-
1078
- ### New File Template
1079
- When the IDE opens with no file (or a new file), this template is auto-inserted:
1080
- ```basic
1081
- ' BazzBasic version {ver_num}
1082
- ' https://ekbass.github.io/BazzBasic/
1083
- ```
1084
-
1085
- ### Beginner's Guide
1086
- - **IDE:** Menu → **Help** → **Beginner's Guide** — opens `https://github.com/EkBass/BazzBasic-Beginners-Guide/releases` in default browser
1087
- - **CLI:** `bazzbasic.exe -guide` or `bazzbasic.exe -help` — prints URL to terminal
1088
-
1089
- ### Online Manual and Rosetta Code
1090
- - **IDE:** Menu → **Help** → **Online Manual** — opens `https://ekbass.github.io/BazzBasic/manual/#/` in default browser
1091
- - **IDE:** Menu → **Help** → **Rosetta Code** — opens `https://rosettacode.org/wiki/Category:BazzBasic` in default browser
1092
- - No CLI equivalents
1093
-
1094
- ### Check for Updates
1095
- - **IDE:** Menu → **Help** → **Check for Updates...** — IDE reports if a newer version is available
1096
- - **CLI:** `bazzbasic.exe -checkupdates`
1097
-
1098
- ### Compile via IDE
1099
- - **Menu → Run → Compile as Exe** — compiles open file to standalone `.exe` (auto-saves first)
1100
- - **Menu → Run → Compile as Library (.bb)** — compiles open file as reusable `.bb` library (auto-saves first)
 
1
  ---
2
+ name: bazzbasic-code
3
+ 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. For changing the interpreter or IDE source code use bazzbasic-interpreter-dev or bazzbasic-ide-dev."
4
  ---
5
 
6
  # BazzBasic Language Reference
7
+ **Version:** 1.6 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64 only (SDL2 via P/Invoke — no Linux, macOS, browser or Android)
8
  **Homepage:** https://ekbass.github.io/BazzBasic/
9
  **GitHub:** https://github.com/EkBass/BazzBasic
10
  **Manual:** https://ekbass.github.io/BazzBasic/manual/#/
 
13
  **Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
14
  **BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
15
  **BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
16
+
17
+ BazzBasic is a BASIC meant for beginners and for small, fun experiments (simple games, quizzes, bouncing balls). It is not a high-performance game engine — keep generated code simple and readable rather than clever.
18
 
19
  ---
20
 
 
22
 
23
  | Rule | Detail |
24
  |------|--------|
25
+ | Variables end with `$` | `name$`, `score$`, `x$` — the suffix does NOT mean string type |
26
+ | Constants end with `#` | `MAX#`, `PI#`, `TITLE#` — `#` only means immutable |
27
  | Arrays declared with `DIM`, end with `$` | `DIM items$` |
28
  | First use of variable requires `LET` | `LET x$ = 0` — after that `x$ = x$ + 1` |
29
  | FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
30
+ | Case-insensitive | Keywords, variables and labels. Only string contents are case-sensitive |
31
+ | Functions defined **before** they are called | Put at top or INCLUDE — forward references don't resolve |
32
  | Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
33
  | Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
34
+ | `DEF FN` scope is fully isolated | Only global `#` constants are visible. No `$` variables, no global arrays. Arrays cannot be passed as parameters — see *Passing Arrays to Functions* |
35
+ | `+` does both add and concatenate | If either side is a string, the other is auto-converted: `"Score: " + 5` → `"Score: 5"`, no `STR()` needed |
 
36
  | Division always returns float | `10 / 3` → `3.333...` |
37
+ | Division by zero returns `0` silently | Guard with `IF b$ = 0 THEN ...` if correctness matters |
38
  | No integer-division operator | Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` |
39
  | Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` — line-numbered message printed |
40
+ | No line-continuation char | Leave an operator at line end or open a `(` — see *Line Continuation* |
41
+ | No line numbers | Never supported. Use `[labels]` |
42
+ | `:` separates statements on one line | `FOR i$ = 1 TO 3 : PRINT i$ : NEXT`. A `:` inside a label like `[sub:init]` is part of the label name, not a separator |
43
+ | `NOT` binds tighter than comparisons | `NOT a$ = b$` means `(NOT a$) = b$`. Parenthesize: `IF NOT (a$ = b$) THEN`, or use `<>` |
44
+ | Comments: `'` or `REM` | `' comment` anywhere on a line; `REM` as a statement, also after `:` (`PRINT x$ : REM note`) |
45
 
46
  ---
47
 
 
58
  FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
59
  LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
60
  CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
61
+ PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + x$, 10, 10, WHITE#
62
  FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
63
  ISSET(arr$(0)) ' expecting error ' returns 0 silently — ISSET only sees scalars
64
  LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
65
+ LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren
66
+ IF NOT a$ = b$ THEN ' QBASIC habit IF NOT (a$ = b$) THEN
67
  ```
68
 
69
+ ---
70
 
71
+ ## When Generating BazzBasic Code
72
+
73
+ - Prefer `FSTRING` over long `+` concatenation chains for multi-variable strings
74
+ - Place `DEF FN` definitions at the top of the file or via `INCLUDE`
75
+ - Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant. They return stable integer handles owned by SDL2 that never change. For many handles, an array is fine: `sprites$("player") = LOADIMAGE(...)`
76
+ - Declare all variables and constants in `[inits]`, not inside loops — this avoids repeated existence checks
77
+ - Precompute colors: `LET WHITE# = RGB(255, 255, 255)` in `[inits]`, never `RGB()` inside a game loop
78
+ - In graphics mode: clear with `LINE (0,0)-(W,H), 0, BF` (much faster than `CLS`), draw text with `DRAWSTRING` (`PRINT` flickers), and wrap each frame in `SCREENLOCK ON` / `SCREENLOCK OFF`
79
+ - 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
80
 
81
  ---
82
 
83
  ## Minimal Valid Program
84
 
85
  ```basic
86
+ [inits] ' [name] is a plain jump label, not a keyword
 
87
  LET name$ = "World"
88
 
89
  [main]
90
  PRINT "Hello, " + name$
91
  END
92
 
93
+ ' subroutines go after END
94
  [sub:drawScreen]
95
+ ' draw
96
  RETURN
97
  ```
98
 
99
+ Programs flow top to bottom. `[inits]` and `[main]` are organizational labels, not required syntax. `END` halts execution; place it at the end of the main flow so control doesn't fall through into subroutines.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
  ---
102
 
103
  ## Line Continuation
104
 
105
+ The lexer figures out continuation automatically using two rules. Never emit `_`, `\`, `&` or any other continuation marker.
106
 
107
  **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:
108
 
 
121
 
122
  Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
123
 
124
+ > `%` is a real binary modulo operator and triggers continuation. `MOD(a, b)` is a function, so it does not (a `)` at line end never continues).
 
125
 
126
  **Rule 2 — open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
127
 
 
132
  )
133
  ```
134
 
 
 
 
 
 
 
 
 
 
 
 
135
  ---
136
 
137
  ## Variables & Constants
 
 
 
138
 
139
+ Variables are dynamically typed, like in JavaScript.
140
+
141
  ```basic
142
+ LET a$ ' Declare without value
143
+ LET b$, c$, d$ ' Multiple declarations without value
144
+ LET e$, f$ = "foo", g$ = 10 ' e$ stays empty, f$ and g$ get values
145
 
146
+ LET name$ = "Alice" ' String
147
+ LET score$ = 0 ' Number
148
 
149
+ LET PI# = 3.14159 ' Constant (immutable)
150
+ LET TITLE# = "My Game" ' String constant
151
  ```
152
 
153
+ **Compound assignment** (variables only — **not** allowed with `#` constants):
154
 
155
  ```basic
156
  LET x$ = 1
157
+ x$ += 5
158
+ x$ -= 3
159
+ x$ *= 2
160
+ x$ /= 4
161
  LET s$ = "Hello"
162
+ s$ += " World" ' concatenation
163
  ```
164
 
165
+ **Scope:** All main-code variables share one scope — `IF`, `FOR`, and `WHILE` do NOT create a new scope.
 
 
166
 
167
  **Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
168
 
 
 
169
  ### Built-in Constants
170
+ - **Boolean:** `TRUE` (`1`), `FALSE` (`0`) — plain numbers. `IF x$ = 1` and `IF x$ = TRUE` are identical.
171
+ - **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e)
172
+ - **System:** `PRG_ROOT#` (program base directory path, ends with a separator)
173
+ - **Version:** `BBVER#` (current BazzBasic version as a string, e.g. `"1.6"`)
174
+ - **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_NUMPAD0#`…`KEY_NUMPAD9#`, `KEY_NUMPAD_PLUS#`, `_MINUS#`, `_MUL#`, `_DIV#`, `_DOT#`, `KEY_LSHIFT#`, `KEY_LCTRL#`, `KEY_RSHIFT#`, `KEY_RCTRL#`, `KEY_LALT#`, `KEY_RALT#`, `KEY_LWIN#`/`KEY_RWIN#`, `KEY_TAB#`, `KEY_BACKSPACE#`, `KEY_INSERT#`, `KEY_DELETE#`, `KEY_HOME#`, `KEY_END#`, `KEY_PGUP#`, `KEY_PGDN#` — see *Keyboard Input*
175
+ - **Gamepad:** see *Gamepad*
176
 
177
  ---
178
 
179
  ## Arrays
 
180
 
181
+ Arrays are fully dynamic and support numeric, string, or mixed indexing.
182
 
183
  ```basic
184
  DIM scores$ ' Declare (required before use)
185
  DIM a$, b$, c$ ' Multiple
186
+ scores$(0) = 95 ' Numeric indices are 0-based
187
+ scores$("name") = "Alice" ' String keys: associative, insertion-ordered
188
  matrix$(0, 1) = "A2" ' Multi-dimensional
189
 
190
  DIM sounds$
191
+ sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
192
+ sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
193
+ sounds$("food", "ham_eat") = "eat_ham.wav"
 
 
194
 
195
+ PRINT LEN(sounds$()) ' 3 - total elements across all groups
196
+ PRINT ROWCOUNT(sounds$()) ' 2 - "guns" & "food"
197
 
198
  DIM car$
199
  car$("manufacturer") = "Ford"
200
  car$("engine") = "1.6 Eco"
 
201
 
202
+ FOR i$ = 0 TO LEN(car$()) - 1 ' No FOREACH — LEN + ARRKEY is the idiom
203
+ LET key$ = ARRKEY(car$(), i$)
204
  PRINT key$; " = "; car$(key$)
205
  NEXT i$
206
  ```
207
 
208
  | Function/Command | Description |
209
  |-----------------|-------------|
210
+ | `LEN(arr$())` | Total element count across all dimensions |
211
  | `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
212
+ | `ARRKEY(arr$(), i)` | Key at 0-based index `i`, in insertion order. Errors on out-of-range index |
213
+ | `HASKEY(arr$(key))` | 1 if exists, 0 if not — **always check before reading possibly uninitialized elements** |
214
  | `DELKEY arr$(key)` | Remove one element |
215
  | `DELARRAY arr$` | Remove entire array (can re-DIM after) |
216
+ | `JOIN dest$, src1$, src2$` | Merge two arrays; matching `src2$` keys overwrite `src1$` at the same level. Use an empty `src1$` to copy an array |
 
 
 
 
217
 
218
+ > `DIM arr$ = value` stores the value at `arr$(0)` — NOT as a scalar. If a scalar is what you want, use `LET`.
219
 
220
  ---
221
 
 
247
  ' Labels, GOTO, GOSUB
248
  [start]
249
  GOSUB [sub:init]
250
+ GOTO [start] ' Avoid jumping into the middle of IF/WHILE blocks
 
251
 
252
  [sub:init]
253
  LET x$ = 0
 
257
  LET target$ = "[menu]"
258
  GOTO target$
259
 
 
260
  SLEEP 2000 ' Pause for milliseconds
261
  END ' Terminate program
262
  ```
263
+
264
+ Labels may contain almost any printable character. Whitespace is trimmed; everything between `[` and `]` is the label name.
265
+
266
  ---
267
 
268
  ## I/O
269
 
270
  | Command | Description |
271
  |---------|-------------|
272
+ | `PRINT expr; expr` | `;` = no space, `,` = tab, can be mixed |
273
  | `PRINT "text";` | Trailing `;` suppresses newline |
274
+ | `INPUT "prompt", var$` | Splits on whitespace/comma; quoted strings are single values |
275
  | `INPUT "prompt", a$, b$` | Multiple values |
276
  | `LINE INPUT "prompt", var$` | Read entire line with spaces |
277
+ | `CLS` | Clear screen (console) |
278
  | `LOCATE row, col` | Move cursor (1-based) |
279
  | `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
280
  | `CURPOS()` | Read cursor as `"row,col"` string |
281
+ | `COLOR fg, bg` | Text colors, palette 0–15 only (`RGB()` does not work here) |
282
+ | `GETCONSOLE(row, col, type)` | Read console cell. type: 0=char (ASCII), 1=fg color, 2=bg color |
283
  | `SHELL("cmd")` | Run shell command, returns output |
284
  | `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
285
 
286
+ **Escape sequences in strings:** `\"` `\n` `\t` `\\` `""`
 
 
 
287
 
288
+ **SHELL + SQLite.** The `sqlite3` CLI is the recommended way to add a database — see the *SQLite Database* page in the manual. When wrapping SQL in SHELL:
289
+ - Always append `2>&1`, or SQL errors disappear silently.
290
+ - Wrap the SQL with `\"`: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
 
 
291
  - In paths use `/` or `\\` — never a single `\`.
292
 
293
  ### Keyboard Input
294
  | Function | Returns | Notes |
295
  |----------|---------|-------|
296
  | `INKEY` | Key value or 0 | Non-blocking |
297
+ | `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection, graphics mode only |
298
  | `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
299
 
300
+ - **Layout-safe keys:** letters, digits, arrows, Space/Enter/Esc, F-keys, numpad and modifiers are the same on every layout — use these for controls. Main-keyboard punctuation (`+ - = , . /`) depends on the layout: never bind controls to `ASC("+")` or `ASC("-")`; use letters or `KEY_NUMPAD_PLUS#` / `KEY_NUMPAD_MINUS#`.
 
 
 
 
 
301
  - Letters always return uppercase codes (`"a"` and `"A"` → `KEY_A#`), in both graphics and console mode.
302
+ - `KEYDOWN` follows the key *label* on the current layout, same as `INKEY`. If no key types a punctuation character without modifiers (e.g. `=` on a Finnish keyboard), `KEYDOWN` of that constant is always FALSE.
303
+ - Numpad Enter = `KEY_ENTER#`.
304
+ - `INKEY` consumes the key: read it once per loop pass (`LET k$ = INKEY`) and compare the variable. A second `INKEY` in the same pass returns 0.
305
+ - Console mode: `INKEY`/`WAITKEY` return the typed character (except letters and special keys); numpad returns the typed digit, not `KEY_NUMPAD*#`.
306
+
 
 
 
307
  ### Mouse (graphics mode only)
308
  `MOUSEX`, `MOUSEY` — cursor position
309
+ `MOUSELEFT`, `MOUSERIGHT`, `MOUSEMIDDLE` — 1 if pressed, 0 otherwise
310
+ `MOUSEHIDE` / `MOUSESHOW` — hide / restore the cursor
 
 
 
 
 
 
 
311
 
312
+ ### Gamepad (console AND graphics mode)
313
  | Function | Returns | Notes |
314
  |----------|---------|-------|
315
  | `GAMEPADS()` | Number of connected pads | Parentheses optional |
 
318
  | `PADNAME(pad)` | String | e.g. `"PS4 Controller"`, `""` if not connected |
319
  | `PADRUMBLE pad, strength, ms` | — (statement) | strength 0.0…1.0, non-blocking, parentheses optional |
320
 
321
+ - Pad index is **0-based**, max 8 pads. Slots are stable while connected (not re-packed on disconnect). Hot-plug works.
322
+ - **No `SCREEN` needed** — works in console programs too.
323
+ - **Disconnected pad = no input, never an error:** `PADBUTTON` → FALSE, `PADAXIS` → 0, `PADNAME` → `""`. Don't guard every read with `IF GAMEPADS() > 0`; use `GAMEPADS()` only to show a "connect a pad" message.
324
+ - Buttons (Xbox naming): `PAD_A#` `PAD_B#` `PAD_X#` `PAD_Y#`, `PAD_UP#` `PAD_DOWN#` `PAD_LEFT#` `PAD_RIGHT#`, `PAD_LB#` `PAD_RB#`, `PAD_LSTICK#` `PAD_RSTICK#`, `PAD_BACK#` `PAD_START#` `PAD_GUIDE#`, `PAD_MISC#`, `PAD_TOUCHPAD#`. PlayStation: A=Cross, B=Circle, X=Square, Y=Triangle. Raw 0–20 valid (16–19 = Elite paddles); outside → error.
325
+ - Axes: `PAD_LX#` `PAD_LY#` `PAD_RX#` `PAD_RY#` `PAD_LT#` `PAD_RT#`. Raw 0–5; outside → error.
326
+ - **Y axis: negative = up**, same as screen Y. `y$ = y$ + PADAXIS(0, PAD_LY#) * SPEED#` is correct — do not invert.
327
+ - **L2/R2 are triggers, not buttons:** read with `PADAXIS(pad, PAD_LT#)`. Never pass an axis constant to `PADBUTTON` — `PADBUTTON(0, PAD_LT#)` silently reads button 4 (`PAD_BACK#`).
328
+ - For one action per press, keep previous state: `IF now$ = TRUE AND was$ = FALSE THEN ...` then `was$ = now$`.
 
329
  - Stick as digital direction: `IF PADAXIS(0, PAD_LX#) < -0.5 THEN ...`
330
+ - Pad OR keyboard: `IF PADBUTTON(0, PAD_LEFT#) OR KEYDOWN(KEY_LEFT#) THEN dx$ = -1`
331
+ - Many third-party pads identify as PS4/Xbox controllers — normal, mapping is still correct.
 
 
 
 
332
 
333
  ---
334
 
335
  ## User-Defined Functions
336
 
337
  ```basic
 
338
  DEF FN Clamp$(val$, lo$, hi$)
339
  IF val$ < lo$ THEN RETURN lo$
340
  IF val$ > hi$ THEN RETURN hi$
341
  RETURN val$
342
  END DEF
343
 
344
+ PRINT FN Clamp$(5, 1, 10) ' ✓ return value used
345
+ LET v$ = FN Clamp$(15, 0, 10) ' ✓
346
  FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
347
  ```
348
 
349
+ - Scope is isolated (see *Critical Rules*). Touching a global array gives: `Global array G$ is not visible inside DEF FN - pass it as a parameter with ASJSON() and rebuild it with ASARRAY()`
350
+ - `DIM` inside a function creates a **fresh, empty, local** array on every call and every recursion level:
351
+ ```basic
352
  DEF FN Count$(x$)
353
+ DIM t$
354
  t$(x$) = 1
355
  RETURN LEN(t$())
356
  END DEF
357
  PRINT FN Count$(1) ' 1
358
  PRINT FN Count$(2) ' 1 (not 2)
359
+ ```
360
+ - Parameters are passed **by value**
 
361
  - Labels inside functions are local — GOTO/GOSUB cannot jump outside
362
+ - Recursion uses the real call stack, so thousands of levels can overflow it. GOSUB/RETURN uses a separate heap-based stack with no such limit.
 
 
363
 
364
  ---
365
 
 
369
  |----------|-------------|
370
  | `ASC(s$)` | ASCII code of first char |
371
  | `CHR(n)` | Character from ASCII code |
372
+ | `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive |
373
  | `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
 
374
  | `INVERT(s$)` | Reverse string |
375
  | `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
376
  | `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars |
 
380
  | `MID(s$, start, len)` | Substring with length |
381
  | `REPEAT(s$, n)` | Repeat string n times |
382
  | `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
383
+ | `SPLIT(arr$, s$, sep$)` | Split into array (keys `0`..`count-1`), returns count. Array is emptied first. `arr$()` also accepted |
384
+ | `SRAND(n)` | Random alphanumeric string of length n. `n = 0` → `""`; **negative n crashes** with an overflow error — never pass an unvalidated length |
385
  | `STR(n)` | Number to string |
386
  | `VAL(s$)` | String to number |
387
  | `SHA256(s$)` | SHA256 hash (64-char hex) |
388
  | `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
389
 
 
 
 
 
 
 
390
  ---
391
 
392
  ## FSTRING — String Interpolation
393
 
394
+ `FSTRING(template$)` substitutes `{{-name-}}` placeholders with the value of variables, constants, or array elements.
395
 
396
  ```basic
397
  LET name$ = "Krisu"
 
400
  ' Output: Hello Krisu, level 5
401
  ```
402
 
403
+ The triple-character markers `{{-` and `-}}` are deliberately unusual. There is no escape syntax — literal `{{-...-}}` is always parsed as a placeholder.
 
 
404
 
405
  | Form | Resolves to |
406
  |------|-------------|
407
+ | `{{-var$-}}` | Variable `var$` |
408
+ | `{{-CONST#-}}` | Constant `CONST#` (built-ins like `{{-PI#-}}` work too) |
409
+ | `{{-arr$(0)-}}` | Element at numeric index `0` |
410
+ | `{{-arr$(i$)-}}` | Element at index from variable `i$` |
411
+ | `{{-arr$(KEY#)-}}` | Element at index from constant `KEY#` |
412
+ | `{{-arr$(name)-}}` | Element at literal string key `"name"` (no quotes inside FSTRING) |
413
+ | `{{-arr$(0, i$)-}}` | Multidimensional, mixed literal and variable indices |
414
+
415
+ **Index resolution** — for each comma-separated index, FSTRING checks:
 
 
 
416
  1. Ends with `$` or `#` → variable / constant lookup. Halts if undefined.
417
+ 2. Parses as a number → numeric index. `arr$(01)` and `arr$(1.0)` both resolve to key `1`.
418
+ 3. Otherwise → literal string key.
419
 
420
+ So `{{-name-}}` (no suffix) is a literal array key, **not** variable `name$`. Always include the suffix.
421
 
422
+ **Notes:** Whitespace inside placeholders is trimmed. Numbers auto-stringify. FSTRING returns a value and must be used — a bare `FSTRING(...)` statement is an error. Undefined names, missing `-}}`, empty `{{--}}`, malformed or uninitialized array access all halt with a line-numbered message.
 
 
 
 
423
 
424
+ **Not supported:** arithmetic, function calls, nested lookups, or quoted literals inside placeholders. Pre-compute into a variable:
 
 
425
 
426
  ```basic
427
  ' ❌ WRONG
 
436
  PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
437
  ```
438
 
439
+ **Full example:**
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
  ```basic
442
  DIM player$
 
445
  player$("level") = 99
446
 
447
  DIM grid$
 
 
448
  grid$(1, 0) = "."
449
  grid$(1, 1) = "X"
450
 
451
  LET row$ = 1
 
452
 
453
  PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
454
  PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
 
455
  END
456
+ ' Output:
457
+ ' Krisu the Bass, lvl 99
458
+ ' Row 1: [.X]
 
 
 
 
459
  ```
460
 
461
  ---
 
466
  |----------|-------------|
467
  | `ABS(n)` | Absolute value |
468
  | `ATAN(n)` | Arc tangent |
469
+ | `ATAN2(y, x)` | Angle in radians from the positive x-axis to point (x, y) |
470
  | `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
471
+ | `INBETWEEN(n, min, max)` | TRUE if min < n < max (strict) |
472
  | `CEIL(n)` / `FLOOR(n)` | Round up / down |
473
  | `CINT(n)` | Round to nearest integer |
474
  | `CLAMP(n, min, max)` | Constrain n to [min, max] |
 
481
  | `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
482
  | `LOG(n)` | Natural logarithm |
483
  | `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
484
+ | `MOD(a, b)` / `a % b` | Remainder (function and operator forms are equivalent) |
 
485
  | `POW(base, exp)` | Power |
486
+ | `RND(n)` | Random integer 0 to n-1 (n > 0) |
487
+ | `RND(0)` | Random float 0.0–1.0 |
488
+ | `ROUND(n)` | Nearest integer, half away from zero (`0.5→1`, `-0.5→-1`) — NOT banker's rounding |
489
  | `SGN(n)` | Sign: -1, 0, or 1 |
490
  | `SQR(n)` | Square root |
491
 
492
+ ### Fast Trigonometry
493
+
494
+ About 20× faster than `SIN(RAD(x))`, 1-degree precision, ~5.6 KB memory. Use for raycasting, sprite rotation, particle systems — anything calling trig hundreds of times per frame.
495
+
496
+ ```basic
497
+ FastTrig(TRUE) ' Enable lookup tables (must call first)
498
+ LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
499
+ LET y$ = FastSin(90)
500
+ LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
501
+ FastTrig(FALSE) ' Free memory
502
+ ```
503
 
504
  ---
505
 
506
+ ## ISSET
507
 
508
+ `ISSET(name)` returns `1` if the named variable (`$`) or constant (`#`) is declared, `0` otherwise. The argument is **not evaluated**, so `ISSET(undef$)` safely returns `0`.
509
+
510
+ - **Scalars only.** `ISSET(arr$)` and `ISSET(arr$(0))` always return `0`, never an error.
511
+ - **Bare name only.** Expressions, string literals, numbers or an empty argument (`ISSET(a$ + b$)`, `ISSET("a$")`, `ISSET(42)`, `ISSET()`) error with "invalid parameter".
512
+ - **Suffix is part of the name:** `a$` and `A#` are different names.
513
+ - **`LET name$` without a value still counts as set.** ISSET reports declaration, not "has a meaningful value".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
 
515
  ```basic
516
+ IF ISSET(playerName$) = FALSE THEN
517
  LET playerName$ = "Anonymous"
518
  END IF
519
  ```
 
530
  FULLSCREEN FALSE ' Windowed
531
  ```
532
 
533
+ Classic modes: 1, 7, 13 = 320×200 · 2, 9 = 640×350 · 12 = 640×480.
 
 
 
 
 
 
 
534
 
535
  ### Drawing Primitives
536
  ```basic
537
+ PSET (x, y), color ' Pixel
538
+ LINE (x1,y1)-(x2,y2), color ' Line
539
+ LINE (x1,y1)-(x2,y2), color, B ' Box outline
540
+ LINE (x1,y1)-(x2,y2), color, BF ' Box filled
541
+ CIRCLE (cx,cy), radius, color ' Circle outline
542
+ CIRCLE (cx,cy), radius, color, 1 ' Circle filled
543
+ PAINT (x, y), fillColor, borderColor ' Flood fill
544
+ LET c$ = POINT(x, y) ' Read pixel color
545
+ LET COL# = RGB(r, g, b) ' Create color (0–255 each)
546
  ```
547
 
548
+ **Color values:** All drawing primitives (`PSET`, `LINE`, `CIRCLE`, `PAINT`, `DRAWSTRING`, `LOADSHAPE`) accept a palette index 0–15 or an `RGB(r, g, b)` value. Never hand-construct packed integers (e.g. `16711680`) — `RGB()` tags its value internally, and a raw integer is misread as a palette index.
549
 
550
  **Palette (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
551
 
 
 
552
  ### Screen Control
553
  ```basic
554
+ SCREENLOCK ON ' Start frame (buffer drawing)
555
+ SCREENLOCK OFF ' Present buffer
556
+ VSYNC(TRUE) ' Enable VSync (default) — loop runs at monitor refresh rate
557
  VSYNC(FALSE) ' Disable VSync (benchmarking)
 
 
 
558
  ```
559
 
560
  ### Shapes & Images
561
  ```basic
562
+ LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
 
 
 
563
  LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
564
+ LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
565
 
566
  ' Sprite sheet — sprites indexed 0-based
567
  DIM sprites$
568
+ LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
569
+ MOVESHAPE sprites$(0), x, y
570
 
571
+ MOVESHAPE RECT#, x, y ' Position
 
 
 
572
  ROTATESHAPE RECT#, angle ' Degrees (absolute)
573
  SCALESHAPE RECT#, scale ' 1.0 = original size
574
  DRAWSHAPE RECT# ' Render to buffer
 
576
  REMOVESHAPE RECT# ' Free memory (always clean up)
577
  ```
578
 
579
+ **Anchor point:** `LOADSHAPE` primitives are center-anchored; `LOADIMAGE` images are top-left-anchored.
580
 
581
+ ### Text Rendering (requires SDL2_ttf.dll next to the interpreter)
 
 
 
 
582
 
583
  ```basic
584
+ DRAWSTRING "Hello!", 100, 200, WHITE# ' Default font: Arial, 16px
585
+ LOADFONT "comic.ttf", 24 ' Becomes the new default
586
+ LOADFONT ' Reset to Arial 16px
 
 
 
 
 
 
587
  ```
588
 
589
+ `DRAWSTRING text, x, y, color` positions the top-left of the text.
590
 
591
  ---
592
 
593
  ## Sound
594
 
595
  ```basic
 
 
596
  LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
597
  SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
598
+ SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
599
+ SOUNDREPEAT(SND_JUMP#) ' Loop continuously
600
+ SOUNDSTOP(SND_JUMP#) ' Stop specific sound
601
  SOUNDSTOPALL ' Stop all sounds
602
  ```
603
 
 
608
  ## File I/O
609
 
610
  ```basic
611
+ LET data$ = FILEREAD("file.txt") ' Read as string
612
+ DIM cfg$ : LET cfg$ = FILEREAD("settings.txt") ' Read as key=value array
613
+ FILEWRITE "save.txt", data$ ' Create/overwrite (array → key=value format)
614
+ FILEAPPEND "log.txt", entry$ ' Append
615
+ LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
616
+ FILEDELETE "temp.dat" ' Delete file
617
  DIM files$
618
+ LET n$ = FILELIST(files$, "levels", "*.txt") ' Names into files$(0..n-1), returns n
619
  ```
620
 
621
+ **key=value parsing:** When `FILEREAD` assigns to a `DIM`'d array, lines `key=value` become `arr$("key")`; lines starting with `#` are comments. Round-trips with `FILEWRITE`. Good for `.env` files:
 
 
622
 
623
  ```basic
624
  DIM env$
625
+ LET env$ = FILEREAD(".env")
626
  LET API_KEY# = env$("OPENAI_API_KEY")
627
  ```
628
 
629
+ **FILELIST:** files only (no folders, not recursive), names only (no paths), sorted alphabetically ignoring case, hidden/system files skipped. The array is cleared first. Pattern supports `*` and `?`, default all files. Missing folder → returns `0`. To open a listed file, prepend the folder: `FILEREAD("levels/" + files$(i$))`.
630
+
631
+ **Paths:** Use `/` or `\\` — never a single `\` (escape char). Relative paths are from `PRG_ROOT#`, which already ends with a separator: `PRG_ROOT# + "data.txt"`.
 
 
 
632
 
633
  ---
634
 
 
638
  LET res$ = HTTPGET("https://api.example.com/data")
639
  LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
640
 
641
+ ' Optional headers
642
  DIM headers$
643
  headers$("Authorization") = "Bearer mytoken"
644
  headers$("Content-Type") = "application/json"
645
  LET res$ = HTTPGET("https://api.example.com/data", headers$)
646
  LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
647
 
648
+ ' Optional timeout in seconds, AFTER headers (default 30, 0 = no limit)
 
649
  LET res$ = HTTPPOST("http://localhost:11434/v1/chat/completions", body$, headers$, 120)
650
  ```
651
 
652
  ### Local HTTP server (LISTEN)
653
 
654
+ Local-only server, typically glue between a static HTML page and a BazzBasic script on the same machine.
655
 
656
  ```basic
657
+ STARTLISTEN 8080 ' Bind 127.0.0.1:8080, no admin needed
658
+ STARTLISTEN 8080, 5000 ' Optional timeout in ms
659
+ LET body$ = GETREQUEST() ' POST/PUT/PATCH body or GET query string ("" on timeout)
660
+ SENDRESPONSE "{""status"":""ok""}" ' Must be called or the browser hangs
661
  STOPLISTEN
662
  ```
663
 
664
+ - **Always pair `GETREQUEST()` with `SENDRESPONSE`.**
665
+ - **Bound to `127.0.0.1` only.** Do not generate code that tries to expose it on a LAN or the internet.
666
+ - **Body or query string only** (no `?`). Headers, method and URL path are not exposed. Parse JSON bodies with `ASARRAY`.
667
+ - **OPTIONS preflight and CORS are automatic.** Don't handle `OPTIONS`; every response carries `Access-Control-Allow-Origin: *`.
668
+ - **One listener at a time.** Call `STOPLISTEN` before another `STARTLISTEN`.
669
+ - **Always 200 OK, always `text/plain`.** To return JSON, put JSON text in the body — browser-side `response.json()` still works.
 
 
 
 
 
670
 
671
  ```basic
672
  STARTLISTEN 8080
 
674
 
675
  LET json$ = GETREQUEST()
676
  DIM data$
677
+ LET count$ = ASARRAY(data$, json$)
 
678
  PRINT "Got name: " + data$("name")
679
 
680
  SENDRESPONSE "{""status"":""ok""}"
 
686
 
687
  ## Arrays & JSON
688
 
689
+ Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`.
690
 
691
  ```basic
692
+ LET json$ = ASJSON(arr$) ' Array → JSON string
 
 
 
693
  DIM data$
694
+ LET count$ = ASARRAY(data$, json$) ' JSON string → array, returns element count
695
+ LOADJSON arr$, "file.json" ' Load JSON file
696
+ SAVEJSON arr$, "file.json" ' Save JSON file
 
 
697
  ```
698
 
699
+ ### Passing Arrays to Functions
 
 
700
 
701
+ Serialize with `ASJSON`, pass the string, rebuild inside with `ASARRAY`. The function gets an independent copy — changes inside do not affect the original. Nested keys work normally.
702
 
703
  ```basic
704
+ DEF FN ProcessPlayer$(data$)
705
+ DIM arr$
706
+ LET count$ = ASARRAY(arr$, data$)
707
+ RETURN arr$("name") + " score:" + arr$("score")
708
+ END DEF
709
+
710
+ [inits]
711
+ DIM player$
712
+ player$("name") = "Alice"
713
+ player$("score") = 9999
714
+ player$("address,city") = "New York"
715
 
716
+ [main]
717
+ LET json$ = ASJSON(player$)
718
+ PRINT FN ProcessPlayer$(json$)
719
+ END
720
+ ```
721
 
722
  ---
723
 
724
  ## Date & Time
725
 
726
  ```basic
727
+ LET t$ = TIME() ' Default "HH:mm:ss" -> "15:21:22"
728
+ LET t2$ = TIME("dd.MM.yyyy") ' .NET DateTime format -> "04.09.2026"
729
  LET t3$ = TIME("dddd") ' -> "Friday"
 
730
  LET start$ = TICKS ' Milliseconds since program start
 
 
731
  ```
732
 
733
+ **Timing — SLEEP and TICKS do different jobs:**
734
+ - **Frame pacing:** in graphics mode, VSync (on by default) waits at `SCREENLOCK OFF`, limiting the loop to the monitor's refresh rate — usually 60 FPS, but 144 FPS on a 144 Hz monitor. Do NOT add `SLEEP 16` to a graphics loop — together they halve the frame rate.
735
+ - **SLEEP ms:** use for deliberate pauses (title screens, "Game Over" delays) and to keep console loops from using 100% CPU (`SLEEP 10` in an `INKEY` polling loop).
736
+ - **TICKS:** use for measuring time — timers, cooldowns, animation speed, and movement that should stay the same speed on every monitor.
737
 
738
  ```basic
739
+ [inits]
740
+ LET running$ = TRUE
741
+ LET lastTick$ = TICKS
742
+ LET delta$
743
+ LET x$ = 0, speed$ = 2 ' several variables in one LET
 
 
 
744
 
745
+ [main]
746
+ WHILE running$
747
+ delta$ = TICKS - lastTick$
748
+ lastTick$ = TICKS
749
+ x$ = x$ + speed$ * delta$ / 16 ' same speed regardless of frame rate
750
+ GOSUB [sub:draw]
751
+ WEND
752
+ END
753
  ```
754
 
755
  ---
 
758
 
759
  ```basic
760
  ' bazzbasic.exe myprog.bas arg1 arg2
761
+ PRINT ARGCOUNT ' 2
762
+ PRINT ARGS(0) ' "arg1"
763
+ PRINT ARGS(1) ' "arg2"
764
  ```
765
 
766
+ 0-based; does not include the interpreter or script name.
767
 
768
  ---
769
 
 
779
  PRINT FN MATHLIB_add$(5, 3)
780
  ```
781
 
782
+ - Library functions can read main-program constants (`#`).
783
+ - `.bb` files are **version-locked** to the build that produced them — recompile after upgrading.
784
+ - **No extension fallback:** `INCLUDE "helpers"` does NOT try `helpers.bas`.
785
+ - **Path resolution:** relative to the including file's directory first, then the program's base path.
786
+ - **Circular includes** halt with `Circular INCLUDE detected: <file>`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
 
788
  ---
789
 
790
  ## Program Structure
791
 
792
  ```basic
793
+ ' ---- 1. FUNCTIONS (or INCLUDE) ----
794
  DEF FN Clamp$(v$, lo$, hi$)
795
  IF v$ < lo$ THEN RETURN lo$
796
  IF v$ > hi$ THEN RETURN hi$
797
  RETURN v$
798
  END DEF
799
 
800
+ ' ---- 2. INIT — declare ALL constants & variables here ----
 
801
  [inits]
802
+ LET SCREEN_W# = 640
803
+ LET SCREEN_H# = 480
804
+ LET MAX_SPEED# = 5
805
+ LET PLAYER_COLOR# = RGB(0, 255, 0)
806
 
807
  SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
808
 
 
815
  WHILE running$
816
  IF INKEY = KEY_ESC# THEN running$ = FALSE
817
  GOSUB [sub:update]
818
+ GOSUB [sub:draw] ' SCREENLOCK OFF + VSync paces the loop to the monitor refresh rate
 
819
  WEND
820
  SOUNDSTOPALL
821
+ END
822
 
823
+ ' ---- 4. SUBROUTINES (or INCLUDE) ----
824
  [sub:update]
825
  IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
826
  IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
 
829
  [sub:draw]
830
  SCREENLOCK ON
831
  LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
832
+ CIRCLE (x$, y$), 10, PLAYER_COLOR#, 1
833
  SCREENLOCK OFF
834
  RETURN
835
  ```
836
 
837
+ **Naming conventions:** variables `camelCase$`, constants `UPPER_SNAKE_CASE#`, functions `PascalCase$`, labels `[gameLoop]` for jump targets and `[sub:name]` for subroutines.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
838
 
839
  ---
840
 
841
+ ## IDE
 
 
 
 
 
 
 
 
 
 
 
 
 
842
 
843
+ From version 1.6, the IDE (`BazzBasic-IDE.exe`) and interpreter (`BazzBasic.exe`) are separate programs in the same release .zip. Launching the interpreter without arguments tries to open the IDE; if that fails, it prints a message to the console.
 
 
844
 
 
845
  | Menu | Items |
846
  |------|-------|
847
+ | **File** | New, Open, Save, Save As, Save All, Close Tab, Close All, Restore Session on Startup¹, Print, Exit |
848
+ | **Edit** | Undo, Redo, Cut, Copy, Paste, Select All, Comment Selection, Uncomment Selection |
849
+ | **Search** | Find, Replace |
850
+ | **View** | Tree View¹ (DEF FN functions and labels on the left), Open Console², Open File Browser², Light Mode¹, Dark Mode (experimental)¹, Syntax Coloring¹ (off = monochrome), Take a Screenshot to Clipboard (IDE window only), Zoom In, Zoom Out |
851
+ | **Run** | Run Program (F5), Compile as Exe, Compile as Library (.bb), Path to BazzBasic.exe³ |
852
+ | **Help** | About, Homepage, Online Manual, Beginner's Guide, Rosetta Code, Check for Updates |
853
+
854
+ ¹ Saved to `%AppData%\BazzBasic\ide.json`
855
+ ² Opens in the current file's folder
856
+ ³ Used if set; otherwise the IDE's own folder, then `PATH`
857
+
858
+ - Compile commands auto-save the file first.
859
+ - Help-menu links open the URLs listed at the top of this guide.
860
+ - CLI equivalents: `bazzbasic.exe -guide` / `-help` prints the Beginner's Guide URL, `bazzbasic.exe -checkupdates` checks for a newer version.
861
+ - New files get this template:
862
+ ```basic
863
+ ' BazzBasic version {ver_num}
864
+ ' https://ekbass.github.io/BazzBasic/
865
+ ```