EkBass commited on
Commit
235d864
·
verified ·
1 Parent(s): 2e3eb41

Upload BazzBasic-AI-guide-23052026.txt

Browse files
Files changed (1) hide show
  1. BazzBasic-AI-guide-23052026.txt +968 -0
BazzBasic-AI-guide-23052026.txt ADDED
@@ -0,0 +1,968 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BazzBasic Language Reference
2
+ **Version:** 1.4b | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64
3
+ **Homepage:** https://ekbass.github.io/BazzBasic/
4
+ **GitHub:** https://github.com/EkBass/BazzBasic
5
+ **Manual:** https://ekbass.github.io/BazzBasic/manual/#/
6
+ **Examples:** https://github.com/EkBass/BazzBasic/tree/main/Examples
7
+ **Rosetta Code:** https://rosettacode.org/wiki/Category:BazzBasic
8
+ **Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
9
+ **BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
10
+ **BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
11
+ **Communities:** https://ekbass.github.io/BazzBasic/communities.html
12
+
13
+ ---
14
+
15
+ ## ⚠️ Critical Rules — Read First
16
+
17
+ | Rule | Detail |
18
+ |------|--------|
19
+ | Variables end with `$` | `name$`, `score$`, `x$` |
20
+ | Constants end with `#` | `MAX#`, `PI#`, `TITLE#` |
21
+ | Arrays declared with `DIM`, end with `$` | `DIM items$` |
22
+ | First use of variable requires `LET` | `LET x$ = 0` — after that `x$ = x$ + 1` |
23
+ | FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
24
+ | Functions defined **before** they are called | Put at top or INCLUDE |
25
+ | Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
26
+ | Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
27
+ | Arrays **cannot** be passed to functions directly | Pass individual elements, or serialize to JSON string — see *Passing Arrays to Functions* section |
28
+ | Case-insensitive | `PRINT`, `print`, `Print` all work |
29
+ | `+` operator does both add and concatenate | `"Hi" + " " + name$` |
30
+ | Division always returns float | `10 / 3` → `3.333...` |
31
+ | Division by zero returns `0` (no error) | Guard with `IF b$ = 0 THEN ...` if needed |
32
+ | No integer-division operator | Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` |
33
+ | Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` — line-numbered message printed |
34
+ | No line-continuation char | Don't use `_`, `\`, or `&` — lexer continues automatically after operators or open `(` |
35
+
36
+ ---
37
+
38
+ ## 🚫 Common AI Mistakes (avoid these)
39
+
40
+ These are the patterns LLMs most often produce when extrapolating from QBASIC, FreeBASIC, or VB. None of them are valid BazzBasic.
41
+
42
+ ```basic
43
+ ' ❌ WRONG ' ✓ CORRECT
44
+ LET x = 5 LET x$ = 5
45
+ LET MAX = 10 LET MAX# = 10
46
+ score$ = 0 ' first use LET score$ = 0
47
+ DEF FN doStuff(a, b) DEF FN DoStuff$(a$, b$)
48
+ FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
49
+ LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
50
+ CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
51
+ PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + STR(x$), 10, 10, RGB(255,255,255)
52
+ FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
53
+ ISSET(arr$(0)) ' expecting error ' returns 0 silently — ISSET only sees scalars
54
+ LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
55
+ LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren — see Line Continuation
56
+ ```
57
+
58
+ **Two more traps that don't fit the table:**
59
+
60
+ - Inside `DEF FN` you can read `#` constants from the outer scope but **not** `$` variables. Pass them as parameters.
61
+ - Arrays cannot be passed to a function. Serialize with `ASJSON()` and rebuild inside the function with `ASARRAY()` — see *Passing Arrays to Functions* below.
62
+
63
+ ---
64
+
65
+ ## Minimal Valid Program
66
+
67
+ ```basic
68
+ [inits]
69
+ LET name$ = "World"
70
+
71
+ [main]
72
+ PRINT "Hello, " + name$
73
+ END
74
+ ```
75
+
76
+ 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.
77
+
78
+ ---
79
+
80
+ ## When Generating BazzBasic Code
81
+
82
+ - Always declare variables with `LET` on first use; subsequent uses don't need it
83
+ - Always include the `$` (variable) or `#` (constant) suffix
84
+ - Prefer `FSTRING` over long `+` concatenation chains for multi-variable strings
85
+ - Place `DEF FN` definitions at the top of the file or via `INCLUDE`
86
+ - Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant
87
+ - In graphics mode, prefer `LINE (0,0)-(W,H), 0, BF` over `CLS`, and `DRAWSTRING` over `PRINT`
88
+ - Wrap each frame's drawing in `SCREENLOCK ON` / `SCREENLOCK OFF`
89
+ - Always use a function's return value — assign with `LET` or consume with `PRINT`
90
+ - 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
91
+
92
+ ---
93
+
94
+
95
+ ## ABOUT
96
+ 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.
97
+
98
+ ### What people have built with it
99
+
100
+ BazzBasic is built for beginners, but it isn't a toy. It can carry real 2D games and even 2.5D graphics work.
101
+
102
+ - https://github.com/EkBass/BazzBasic/blob/main/Examples/Voxel_terrain.bas
103
+ 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.
104
+ - https://github.com/EkBass/BazzBasic/blob/main/Examples/Raycaster_3d_optimized.bas
105
+ 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.
106
+ - https://ek-bass.itch.io/rgb-vision
107
+ A speedrun platformer made for Jam for All BASIC Dialects #7 (itch.io).
108
+ - https://github.com/EkBass/BazzBasic/blob/main/Examples/2D_maze_FOV_demo_console.bas
109
+ 2D maze with FOV in your console
110
+ - https://ek-bass.itch.io/eliza-bazzbasic-edition
111
+ A classic DOCTOR script from the 60s which made people honestly believe they are talking to a real human. Grandmother of modern AIs.
112
+ - https://github.com/EkBass/BazzBasic/blob/main/Examples/rosetta-code/BrainFuck.bas
113
+ BrainFuck interpreter. One of the first programs ever done with BazzBasic.
114
+ - https://github.com/EkBass/BazzBasic/blob/main/Examples/Anthropic_Claude_API_call.bas & https://github.com/EkBass/BazzBasic/blob/main/Examples/OpenAI_request.bas
115
+ Anthropic Claude API and OpenAI ChatGPT API available, both with less than 50 lines of code.
116
+
117
+ **Note:** All ".../Examples/..." codes are delivered with BazzBasic and they are found on the BazzBasic executable folder.
118
+
119
+ ### STORY
120
+ 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.
121
+ To arouse your curiosity.
122
+ *EkBass*, author of BazzBasic
123
+
124
+ ---
125
+
126
+ ## Case sensitivity
127
+ BazzBasic is not case-sensitive except with string contents.
128
+ ```basic
129
+ let blaa$ = "Hello"
130
+ PriNT BLAA$ ' output: Hello
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Line Continuation
136
+
137
+ BazzBasic has **no line-continuation character**. Do not generate `_` (VBA), `\` (Python), or `&` (other dialects). The lexer figures out continuation automatically using two rules.
138
+
139
+ **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:
140
+
141
+ ```basic
142
+ LET total$ = price$ * count$ -
143
+ discount$
144
+
145
+ IF score$ >= 0 AND
146
+ score$ <= 100 THEN
147
+ PRINT "Valid"
148
+ END IF
149
+
150
+ LET counter$ +=
151
+ step$
152
+ ```
153
+
154
+ Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
155
+
156
+ > `MOD` is a function `MOD(a, b)`, not a binary operator — it does not trigger continuation. Use `%` for the modulo operator.
157
+
158
+ **Rule 2 — open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
159
+
160
+ ```basic
161
+ LET dist$ = DISTANCE(
162
+ x1$, y1$,
163
+ x2$, y2$
164
+ )
165
+ ```
166
+
167
+ Both rules combine:
168
+
169
+ ```basic
170
+ LET total$ = (
171
+ base$ +
172
+ tax$
173
+ )
174
+ ```
175
+
176
+ **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.
177
+
178
+ ---
179
+
180
+ ## Variables & Constants
181
+ Variables and constants must be declared with LET before they can be used.
182
+ BazzBasic variables are not typed, but work the same way as in JavaScript, for example.
183
+ A variable needs the suffix $ which often is linked as STRING in traditional basic variants.
184
+
185
+ Variables require suffix "$". Constants require suffix "#".
186
+ The suffix does not define data type — only "#" indicates immutability.
187
+ ```basic
188
+ LET a$ ' Declare variable without value
189
+ LET b$, c$, d$ ' Multiple variable declarations without value
190
+ LET e$, f$ = "foo", g$ = 10 ' Multiple variable declaration, e$ stays empty, f$ and g$ gets values
191
+
192
+ LET name$ = "Alice" ' String variable
193
+ LET score$ = 0 ' Numeric variable
194
+
195
+ LET PI# = 3.14159 ' Constant (immutable)
196
+ LET TITLE# = "My Game" ' String constant
197
+ ```
198
+
199
+ **Compound assignment operators** (variables only — **not** allowed with `#` constants):
200
+
201
+ ```basic
202
+ LET x$ = 1
203
+ x$ += 5 ' add
204
+ x$ -= 3 ' subtract
205
+ x$ *= 2 ' multiply
206
+ x$ /= 4 ' divide
207
+ LET s$ = "Hello"
208
+ s$ += " World" ' string concatenation
209
+ ```
210
+
211
+ **Scope:** All main-code variables share one scope (IF, FOR, and WHILE do NOT create new scope).
212
+ Main-code variables ($) are NOT accessible inside DEF FN
213
+ `DEF FN` functions are fully isolated — only global constants (`#`) accessible inside.
214
+
215
+ **Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
216
+
217
+ ---
218
+
219
+ ### Built-in Constants
220
+ - **Boolean:** `TRUE`, `FALSE`
221
+ - **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e) — `#` suffix required
222
+ - **System:** `PRG_ROOT#` (program base directory path)
223
+ - **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.
224
+
225
+ ---
226
+
227
+ ## Arrays
228
+ BazzBasic arrays are fully dynamic and support numeric, string, or mixed indexing.
229
+
230
+
231
+ ```basic
232
+ DIM scores$ ' Declare (required before use)
233
+ DIM a$, b$, c$ ' Multiple
234
+ scores$(0) = 95 ' Numeric indices are 0-based.
235
+ scores$("name") = "Alice" ' String keys are associative and unordered.
236
+ matrix$(0, 1) = "A2" ' Multi-dimensional
237
+
238
+ DIM sounds$
239
+ sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
240
+ sounds$("guns", "shotgun_reload") = "reload_shotgun.wav"
241
+ sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
242
+ sounds$("guns", "ak47_reload") = "reload_ak47.wav"
243
+ sounds$("food", "ham_eat") = "eat_ham.wav"
244
+
245
+ PRINT LEN(sounds$()) ' 5 as full size of arrayas there is total of 5 values in array
246
+ PRINT ROWCOUNT(sounds$()) ' 2, "guns" & "food"
247
+ ```
248
+
249
+ | Function/Command | Description |
250
+ |-----------------|-------------|
251
+ | `LEN(arr$())` | Total element count (LEN counts all nested elements across all dimensions) |
252
+ | `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
253
+ | `HASKEY(arr$(key))` | 1 if exists, 0 if not |
254
+ | `DELKEY arr$(key)` | Remove one element |
255
+ | `DELARRAY arr$` | Remove entire array (can re-DIM after) |
256
+ | `JOIN dest$, src1$, src2$` | Merge two arrays; `src2$` keys overwrite `src1$`. Use empty `src1$` as `COPYARRAY`. |
257
+
258
+ **JOIN** Matching keys from src2$ overwrite src1$ at the same level
259
+
260
+ **Always check with `HASKEY` before reading uninitialized elements.**
261
+
262
+ ---
263
+
264
+ ## Control Flow
265
+
266
+ ```basic
267
+ ' Block IF
268
+ IF score$ >= 90 THEN
269
+ PRINT "A"
270
+ ELSEIF score$ >= 80 THEN
271
+ PRINT "B"
272
+ ELSE
273
+ PRINT "F"
274
+ END IF ' ENDIF also works
275
+
276
+ ' One-line IF
277
+ IF lives$ = 0 THEN GOTO [game_over]
278
+ IF key$ = KEY_ESC# THEN GOTO [menu] ELSE GOTO [play]
279
+
280
+ ' FOR (auto-declares variable)
281
+ FOR i$ = 1 TO 10 STEP 2 : PRINT i$ : NEXT
282
+ FOR i$ = 10 TO 1 STEP -1 : PRINT i$ : NEXT
283
+
284
+ ' WHILE
285
+ WHILE x$ < 100
286
+ x$ = x$ * 2
287
+ WEND
288
+
289
+ ' Labels, GOTO, GOSUB
290
+ [start]
291
+ GOSUB [sub:init]
292
+ ' Avoid jumping into the middle of logical blocks (e.g. inside IF/WHILE)
293
+ GOTO [start]
294
+
295
+ [sub:init]
296
+ LET x$ = 0
297
+ RETURN
298
+
299
+ ' Dynamic jump (variable must contain "[label]" with brackets)
300
+ LET target$ = "[menu]"
301
+ GOTO target$
302
+
303
+ ' Other
304
+ SLEEP 2000 ' Pause for milliseconds
305
+ END ' Terminate program
306
+ ```
307
+ **Note:** Labels are case-insensitive and may contain almost any printable character.
308
+ Whitespace is trimmed. Everything between "[" and "]" is treated as the label name.
309
+ ---
310
+
311
+ ## I/O
312
+
313
+ | Command | Description |
314
+ |---------|-------------|
315
+ | `PRINT expr; expr` | `;` = no space, `,` = tab |
316
+ | `PRINT "text";` | Trailing `;` suppresses newline |
317
+ | `INPUT "prompt", var$` | Splits on whitespace/comma |
318
+ | `INPUT "prompt", a$, b$` | Multiple values |
319
+ | `LINE INPUT "prompt", var$` | Read entire line with spaces |
320
+ | `CLS` | Clear screen |
321
+ | `LOCATE row, col` | Move cursor (1-based) |
322
+ | `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
323
+ | `CURPOS()` | Read cursor as `"row,col"` string |
324
+ | `COLOR fg, bg` | Text colors (0–15 palette) |
325
+ | `SHELL("cmd")` | Run shell command, returns output |
326
+ | `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
327
+
328
+ ' ; prints without spacing
329
+ ' , prints tab separation
330
+ ' Both can be mixed in a single PRINT statement
331
+ ' INPUT splits on whitespace and comma; quoted strings are treated as single values
332
+
333
+ **Escape sequences in strings:** `\"` `\n` `\t` `\\`
334
+
335
+ **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:
336
+ - Always append `2>&1` to the command, or SQL errors disappear silently.
337
+ - Use `\"` (BazzBasic escape) to wrap the SQL for the OS shell: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
338
+ - In paths use `/` or `\\` — never a single `\`.
339
+
340
+ ### Keyboard Input
341
+ | Function | Returns | Notes |
342
+ |----------|---------|-------|
343
+ | `INKEY` | Key value or 0 | Non-blocking |
344
+ | `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection; KEYDOWN only works in graphics mode |
345
+ | `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
346
+
347
+ ### Mouse (graphics mode only)
348
+ `MOUSEX`, `MOUSEY` — cursor position
349
+ `MOUSELEFT`, MOUSERIGHT, MOUSEMIDDLE — return 1 if pressed, 0 otherwise
350
+ `MOUSEHIDE` — hide the mouse cursor (graphics screen only)
351
+ `MOUSESHOW` — restore the mouse cursor (graphics screen only)
352
+
353
+ ### Console Read
354
+ Returns numeric or character depending on type parameter
355
+ `GETCONSOLE(row, col, type)` — type: 0=char (ASCII), 1=fg color, 2=bg color
356
+
357
+ ---
358
+
359
+ ## User-Defined Functions
360
+
361
+ ```basic
362
+ ' Define BEFORE calling. Name must end with $.
363
+ DEF FN Clamp$(val$, lo$, hi$)
364
+ IF val$ < lo$ THEN RETURN lo$
365
+ IF val$ > hi$ THEN RETURN hi$
366
+ RETURN val$
367
+ END DEF
368
+
369
+ PRINT FN Clamp$(5, 1, 10) ' ✓ OK — return value used
370
+ LET v$ = FN Clamp$(15, 0, 10) ' ✓ OK
371
+ FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
372
+ ' Return value must be assigned with LET or consumed by PRINT — there is no way to silently discard it.
373
+ ```
374
+
375
+ - Isolated scope: no access to global variables, only global constants (`#`)
376
+ - Parameters passed **by value**
377
+ - Labels inside functions are local — GOTO/GOSUB cannot jump outside
378
+ - Supports recursion
379
+ - Arrays as parameters not allowed. Use ASJSON to make array as JSON-string to pass it.
380
+ - Use `INCLUDE` to load functions from separate files if many
381
+
382
+ ---
383
+
384
+ ## String Functions
385
+
386
+ | Function | Description |
387
+ |----------|-------------|
388
+ | `ASC(s$)` | ASCII code of first char |
389
+ | `CHR(n)` | Character from ASCII code |
390
+ | `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive by default |
391
+ | `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
392
+ | `INSTR(start, s$, search$)` | Search from position (case-sensitive) |
393
+ | `INVERT(s$)` | Reverse string |
394
+ | `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
395
+ | `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars |
396
+ | `LEN(s$)` | String length |
397
+ | `LTRIM(s$)` / `RTRIM(s$)` / `TRIM(s$)` | Strip whitespace |
398
+ | `MID(s$, start)` | Substring from start (1-based) |
399
+ | `MID(s$, start, len)` | Substring with length |
400
+ | `REPEAT(s$, n)` | Repeat string n times |
401
+ | `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
402
+ | `SPLIT(arr$, s$, sep$)` | Split into array, returns count. Expects array is declared with DIM |
403
+ | `SRAND(n)` | Random alphanumeric string of length n |
404
+ | `STR(n)` | Number to string |
405
+ | `VAL(s$)` | String to number |
406
+ | `SHA256(s$)` | SHA256 hash (64-char hex) |
407
+ | `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
408
+
409
+ ---
410
+
411
+ ## FSTRING — String Interpolation
412
+
413
+ `FSTRING(template$)` substitutes `{{-name-}}` placeholders inside a template string with the value of variables, constants, or array elements. Preferred over long `+` concatenation chains.
414
+
415
+ ```basic
416
+ LET name$ = "Krisu"
417
+ LET LEVEL# = 5
418
+ PRINT FSTRING("Hello {{-name$-}}, level {{-LEVEL#-}}")
419
+ ' Output: Hello Krisu, level 5
420
+ ```
421
+
422
+ 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.
423
+
424
+ ### Placeholder forms
425
+
426
+ | Form | Resolves to |
427
+ |------|-------------|
428
+ | `{{-var$-}}` | Value of variable `var$` |
429
+ | `{{-CONST#-}}` | Value of constant `CONST#` |
430
+ | `{{-arr$(0)-}}` | Array element at numeric index `0` |
431
+ | `{{-arr$(i$)-}}` | Array element at index taken from variable `i$` |
432
+ | `{{-arr$(KEY#)-}}` | Array element at index taken from constant `KEY#` |
433
+ | `{{-arr$(name)-}}` | Array element at literal string key `"name"` (no quotes inside FSTRING) |
434
+ | `{{-arr$(0, i$)-}}` | Multidimensional element, mixed literal and variable indices |
435
+
436
+ ### Index resolution rule (array access)
437
+
438
+ For each comma-separated index, FSTRING looks at the last character:
439
+
440
+ 1. Ends with `$` or `#` → variable / constant lookup. Halts if undefined.
441
+ 2. Parses as a number (`0`, `1.5`, `-3`) → numeric index. `arr$(01)` and `arr$(1.0)` both resolve to key `1`.
442
+ 3. Otherwise → literal string key. This is what lets `{{-player$(name)-}}` read what was stored with `player$("name") = ...`.
443
+
444
+ ### Notes
445
+
446
+ - Whitespace inside placeholders is trimmed: `{{- name$ -}}` ≡ `{{-name$-}}`.
447
+ - Numbers auto-stringify — no `STR()` needed for numeric variables, constants, or array elements.
448
+ - FSTRING returns a value; you must use it (`LET`, `PRINT`, pass to function). Calling it as a bare statement is an error.
449
+ - Errors halt the program with a line-numbered message: undefined variable, missing closing `-}}`, empty placeholder `{{--}}`, malformed array access, uninitialized array element.
450
+
451
+ ### Not supported (intentional)
452
+
453
+ No arithmetic, function calls, nested lookups, or quoted string literals inside placeholders. Pre-compute into a variable and reference that:
454
+
455
+ ```basic
456
+ ' ❌ WRONG
457
+ PRINT FSTRING("Total: {{-a$ + 5-}}")
458
+ PRINT FSTRING("Name: {{-UCASE(name$)-}}")
459
+ PRINT FSTRING("{{-arr$(arr2$(0))-}}")
460
+
461
+ ' ✓ RIGHT
462
+ LET total$ = a$ + 5
463
+ LET upper$ = UCASE(name$)
464
+ LET k$ = arr2$(0)
465
+ PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
466
+ ```
467
+
468
+ ### Common AI mistakes with FSTRING
469
+
470
+ ```basic
471
+ ' ❌ WRONG ' ✓ CORRECT
472
+ FSTRING("Hi {{name$}}") FSTRING("Hi {{-name$-}}")
473
+ FSTRING("Hi {-name$-}") FSTRING("Hi {{-name$-}}")
474
+ FSTRING("Hi {{-name-}}") ' array key FSTRING("Hi {{-name$-}}")
475
+ FSTRING("Hi {{-name$-}}") ' as stmt LET s$ = FSTRING("Hi {{-name$-}}")
476
+ ```
477
+
478
+ 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.
479
+
480
+ ### Full working example
481
+
482
+ ```basic
483
+ DIM player$
484
+ player$("name") = "Krisu"
485
+ player$("class") = "Bass"
486
+ player$("level") = 99
487
+
488
+ DIM grid$
489
+ grid$(0, 0) = "X"
490
+ grid$(0, 1) = "O"
491
+ grid$(1, 0) = "."
492
+ grid$(1, 1) = "X"
493
+
494
+ LET row$ = 1
495
+ LET PI# = 3.14
496
+
497
+ PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
498
+ PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
499
+ PRINT FSTRING("Pi is roughly {{-PI#-}}")
500
+ END
501
+ ```
502
+
503
+ Output:
504
+ ```
505
+ Krisu the Bass, lvl 99
506
+ Row 1: [.X]
507
+ Pi is roughly 3.14
508
+ ```
509
+
510
+ ---
511
+
512
+ ## Math Functions
513
+
514
+ | Function | Description |
515
+ |----------|-------------|
516
+ | `ABS(n)` | Absolute value |
517
+ | `ATAN(n)` | Arc tangent |
518
+ | `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 |
519
+ | `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
520
+ | `INBETWEEN(n, min, max)` | TRUE if min < n < max (strictly between, not equal) |
521
+ | `CEIL(n)` / `FLOOR(n)` | Round up / down |
522
+ | `CINT(n)` | Round to nearest integer |
523
+ | `CLAMP(n, min, max)` | Constrain n to [min, max] |
524
+ | `COS(n)` / `SIN(n)` / `TAN(n)` | Trig (radians) |
525
+ | `DEG(rad)` / `RAD(deg)` | Radians ↔ degrees |
526
+ | `DISTANCE(x1,y1, x2,y2)` | 2D Euclidean distance |
527
+ | `DISTANCE(x1,y1,z1, x2,y2,z2)` | 3D Euclidean distance |
528
+ | `EXP(n)` | e^n |
529
+ | `INT(n)` | Truncate toward zero |
530
+ | `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
531
+ | `LOG(n)` | Natural logarithm |
532
+ | `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
533
+ | `MOD(a, b)` | Remainder |
534
+ | `POW(base, exp)` | Power |
535
+ | `RND(n)` | Random integer 0 to n-1 if n > 0 |
536
+ | `RND(0)` | Float between 0.0 and 1.0 (IE: 0.5841907423666761) |
537
+ | `ROUND(n)` | Standard rounding |
538
+ | `SGN(n)` | Sign: -1, 0, or 1 |
539
+ | `SQR(n)` | Square root |
540
+
541
+ **Math constants:** `PI#`, `HPI#` (PI/2), `QPI#` (PI/4), `TAU#` (PI*2), `EULER#`
542
+
543
+ ---
544
+
545
+ ## Variable Functions
546
+
547
+ | Function | Description |
548
+ |----------|-------------|
549
+ | `ISSET(name)` | `1` if the named variable (`$`) or constant (`#`) is declared, `0` otherwise. Argument is **not evaluated** — `ISSET(undef$)` safely returns `0`. |
550
+
551
+ `ISSET` is the only language-introspection function and it has tight rules:
552
+
553
+ - **Scalars only.** Variables (`$`) and constants (`#`). Arrays and array elements are stored separately — `ISSET(arr$)` and `ISSET(arr$(0))` always return `0`, never an error.
554
+ - **Bare name only.** No expressions, no string literals, no numbers. These all error with "invalid parameter":
555
+ ```basic
556
+ ISSET(a$ + b$) ' WRONG: expression
557
+ ISSET("a$") ' WRONG: string literal
558
+ ISSET(42) ' WRONG: number
559
+ ISSET() ' WRONG: empty
560
+ ```
561
+ - **Suffix is part of the name.** `a$` and `A#` are different names:
562
+ ```basic
563
+ LET a$ = "foo"
564
+ PRINT ISSET(a$) ' 1
565
+ PRINT ISSET(A#) ' 0
566
+ ```
567
+ - **`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".
568
+
569
+ Typical use is guarding optional setup:
570
+
571
+ ```basic
572
+ IF NOT ISSET(playerName$) THEN
573
+ LET playerName$ = "Anonymous"
574
+ END IF
575
+ ```
576
+
577
+ ---
578
+
579
+ ## Graphics
580
+
581
+ ```basic
582
+ SCREEN 12 ' 640×480 VGA
583
+ SCREEN 0, 800, 600 ' Custom size
584
+ SCREEN 0, 1024, 768, "My Game" ' Custom size + title
585
+ FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
586
+ FULLSCREEN FALSE ' Windowed
587
+ ```
588
+
589
+ | Mode | Resolution |
590
+ |------|-----------|
591
+ | 1 | 320×200 |
592
+ | 2 | 640×350 |
593
+ | 7 | 320×200 |
594
+ | 9 | 640×350 |
595
+ | 12 | 640×480 ← recommended |
596
+ | 13 | 320×200 |
597
+
598
+ ### Drawing Primitives
599
+ ```basic
600
+ PSET (x, y), color ' Pixel
601
+ LINE (x1,y1)-(x2,y2), color ' Line
602
+ LINE (x1,y1)-(x2,y2), color, B ' Box outline
603
+ LINE (x1,y1)-(x2,y2), color, BF ' Box filled (FAST — use instead of CLS)
604
+ CIRCLE (cx,cy), radius, color ' Circle outline
605
+ CIRCLE (cx,cy), radius, color, 1 ' Circle filled
606
+ PAINT (x, y), fillColor, borderColor ' Flood fill
607
+ LET c$ = POINT(x, y) ' Read pixel color
608
+ LET col$ = RGB(r, g, b) ' Create color (0–255 each)
609
+ ```
610
+
611
+ **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.
612
+
613
+ **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
614
+
615
+ > 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)`.
616
+
617
+ ### Screen Control
618
+ ```basic
619
+ SCREENLOCK ON ' Buffer drawing (start frame)
620
+ SCREENLOCK OFF ' Present buffer (end frame)
621
+ VSYNC(TRUE) ' Enable VSync (default, ~60 FPS)
622
+ VSYNC(FALSE) ' Disable VSync (benchmarking)
623
+ CLS ' Clear screen
624
+ ' Use CLS only with console, in graphics screen its slow
625
+ ' With graphics screen, prefer LINE BF
626
+ ```
627
+
628
+ ### Shapes & Images
629
+ ```basic
630
+ ' Create shape
631
+ ' LOADSHAPE and LOADIMAGE return a stable integer handle — never reassigned.
632
+ ' SDL2 owns the resource; your code only ever holds this one reference. Use constants.
633
+ LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
634
+ LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
635
+ LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
636
+
637
+ ' Sprite sheet — sprites indexed 1-based
638
+ DIM sprites$
639
+ LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
640
+ MOVESHAPE sprites$(1), x, y ' sprites$(1) = first sprite
641
+
642
+ ' Transform
643
+ MOVESHAPE RECT#, x, y ' Position by center point
644
+ ROTATESHAPE RECT#, angle ' Degrees (absolute)
645
+ SCALESHAPE RECT#, scale ' 1.0 = original size
646
+ DRAWSHAPE RECT# ' Render to buffer
647
+ SHOWSHAPE RECT# / HIDESHAPE RECT# ' Toggle visibility
648
+ REMOVESHAPE RECT# ' Free memory (always clean up)
649
+ ```
650
+
651
+
652
+ ---
653
+
654
+ ### Text Rendering (SDL2_ttf.dll required)
655
+ #### DRAWSTRING & LOADFONT
656
+
657
+
658
+ ```basic
659
+ ' Default font (Arial)
660
+ DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
661
+
662
+ ' Load alternative font — becomes the new default
663
+ LOADFONT "comic.ttf", 24
664
+ DRAWSTRING "Hello!", 100, 200, RGB(255, 255, 255)
665
+
666
+ ' Reset to Arial
667
+ LOADFONT
668
+ ```
669
+
670
+ `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.
671
+
672
+ ---
673
+
674
+ ## Sound
675
+
676
+ ```basic
677
+ ' LOADSOUND returns a stable integer handle — SDL2 manages the resource.
678
+ ' The handle never changes; store it in a constant to protect it from accidental reassignment.
679
+ LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
680
+ SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
681
+ SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
682
+ SOUNDREPEAT(SND_JUMP#) ' Loop continuously
683
+ SOUNDSTOP(SND_JUMP#) ' Stop specific sound
684
+ SOUNDSTOPALL ' Stop all sounds
685
+ ```
686
+
687
+ Load all sounds at startup. Call `SOUNDSTOPALL` before `END`.
688
+
689
+ ---
690
+
691
+ ## File I/O
692
+
693
+ ```basic
694
+ LET data$ = FileRead("file.txt") ' Read as string
695
+ DIM cfg$ : LET cfg$ = FileRead("settings.txt") ' Read as key=value array
696
+ FILEWRITE "save.txt", data$ ' Create/overwrite
697
+ FILEAPPEND "log.txt", entry$ ' Append
698
+ LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
699
+ FILEDELETE "temp.dat" ' Delete file
700
+ ```
701
+
702
+ **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.
703
+
704
+ ```basic
705
+ DIM env$
706
+ LET env$ = FileRead(".env")
707
+ LET API_KEY# = env$("OPENAI_API_KEY")
708
+ ```
709
+
710
+ **Paths:** Use `/` or `\\` — never single `\` (it's an escape char). Relative paths are from `PRG_ROOT#`.
711
+ **FileWrite with array** saves in key=value format (round-trips with FileRead).
712
+
713
+ ---
714
+
715
+ ## Network
716
+
717
+ ```basic
718
+ LET res$ = HTTPGET("https://api.example.com/data")
719
+ LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
720
+
721
+ ' With headers (optional last parameter)
722
+ DIM headers$
723
+ headers$("Authorization") = "Bearer mytoken"
724
+ headers$("Content-Type") = "application/json"
725
+ LET res$ = HTTPGET("https://api.example.com/data", headers$)
726
+ LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
727
+ ```
728
+
729
+ ### Local HTTP server (LISTEN)
730
+
731
+ 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.
732
+
733
+ ```basic
734
+ STARTLISTEN 8080 ' bind 127.0.0.1:8080, no admin needed
735
+ STARTLISTEN 8080, 5000 ' optional timeout in ms
736
+ LET body$ = GETREQUEST() ' POST/PUT/PATCH body, or GET query string ("" on timeout)
737
+ SENDRESPONSE "{""status"":""ok""}" ' must be called or browser hangs
738
+ STOPLISTEN
739
+ ```
740
+
741
+ Important rules:
742
+
743
+ - **Always pair `GETREQUEST()` with `SENDRESPONSE`.** The browser is waiting on the response. Forgetting `SENDRESPONSE` makes the page hang.
744
+ - **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.
745
+ - **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$)`.
746
+ - **OPTIONS preflight is automatic.** Do NOT write code that handles `OPTIONS` — it is consumed silently and never reaches user code.
747
+ - **CORS is automatic.** Every response carries `Access-Control-Allow-Origin: *`. No need to set it manually.
748
+ - **One listener at a time.** Calling `STARTLISTEN` while one is already active is an error. Call `STOPLISTEN` first.
749
+ - **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.
750
+
751
+ Typical receive-and-process pattern:
752
+
753
+ ```basic
754
+ STARTLISTEN 8080
755
+ PRINT "Waiting for browser..."
756
+
757
+ LET json$ = GETREQUEST()
758
+ DIM data$
759
+ LET data$ = ASARRAY(json$)
760
+
761
+ PRINT "Got name: " + data$("name")
762
+
763
+ SENDRESPONSE "{""status"":""ok""}"
764
+ STOPLISTEN
765
+ END
766
+ ```
767
+
768
+ ---
769
+
770
+ ## Arrays & JSON
771
+
772
+ Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`
773
+
774
+ ```basic
775
+ ' Array → JSON string
776
+ LET json$ = ASJSON(arr$)
777
+
778
+ ' JSON string → array (returns element count)
779
+ DIM data$
780
+ LET count$ = ASARRAY(data$, json$)
781
+
782
+ ' Load/save JSON files
783
+ LOADJSON arr$, "file.json"
784
+ SAVEJSON arr$, "file.json"
785
+ ```
786
+
787
+ ---
788
+
789
+ ## Fast Trigonometry
790
+
791
+ ~20× faster than `SIN(RAD(x))`, 1-degree precision. Uses ~5.6 KB memory.
792
+
793
+ ```basic
794
+ FastTrig(TRUE) ' Enable lookup tables (must call first)
795
+ LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
796
+ LET y$ = FastSin(90)
797
+ LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
798
+ FastTrig(FALSE) ' Free memory
799
+ ```
800
+
801
+ Use for raycasting, sprite rotation, particle systems, any high-freq trig.
802
+
803
+ ---
804
+
805
+ ## Command-Line Arguments
806
+
807
+ ```basic
808
+ ' bazzbasic.exe myprog.bas arg1 arg2
809
+ PRINT ARGCOUNT ' number of args (2 in this example)
810
+ PRINT ARGS(0) ' first arg → "arg1"
811
+ PRINT ARGS(1) ' second arg → "arg2"
812
+ ```
813
+
814
+ `ARGCOUNT` and `ARGS(n)` are 0-based; ARGS does not include the interpreter or script name.
815
+
816
+ ---
817
+
818
+ ## Libraries & INCLUDE
819
+
820
+ ```basic
821
+ INCLUDE "helpers.bas" ' Insert source at this point
822
+ INCLUDE "MathLib.bb" ' Load compiled library
823
+
824
+ ' Compile library (functions only — no loose code)
825
+ ' bazzbasic.exe -lib MathLib.bas → MathLib.bb
826
+ ' Function names auto-prefixed: MATHLIB_functionname$
827
+ PRINT FN MATHLIB_add$(5, 3)
828
+ ```
829
+
830
+ Library functions can read main-program constants (`#`). `.bb` files are version-locked.
831
+
832
+ ---
833
+
834
+ ## Passing Arrays to Functions
835
+
836
+ 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+.
837
+
838
+ ```basic
839
+ DEF FN ProcessPlayer$(data$)
840
+ DIM arr$
841
+ LET count$ = ASARRAY(arr$, data$)
842
+ RETURN arr$("name") + " score:" + arr$("score")
843
+ END DEF
844
+
845
+ [inits]
846
+ DIM player$
847
+ player$("name") = "Alice"
848
+ player$("score") = 9999
849
+ player$("address,city") = "New York"
850
+
851
+ [main]
852
+ LET json$ = ASJSON(player$)
853
+ PRINT FN ProcessPlayer$(json$)
854
+ END
855
+ ```
856
+
857
+ **Notes:**
858
+ - The function receives a full independent copy — changes inside do not affect the original array
859
+ - Nested keys work normally: `arr$("address,city")` etc.
860
+ - Overhead is similar to copying an array manually; acceptable for most use cases
861
+
862
+ ---
863
+
864
+ ## Program Structure
865
+
866
+ ```basic
867
+ ' ---- 1. FUNCTIONS (or INCLUDE "functions.bas/bb") ----
868
+ DEF FN Clamp$(v$, lo$, hi$)
869
+ IF v$ < lo$ THEN RETURN lo$
870
+ IF v$ > hi$ THEN RETURN hi$
871
+ RETURN v$
872
+ END DEF
873
+
874
+ ' ---- 2. INIT (declare ALL constants & variables here, not inside loops) ----
875
+ ' Performance: variables declared outside loops avoid repeated existence checks.
876
+ [inits]
877
+ LET SCREEN_W# = 640
878
+ LET SCREEN_H# = 480
879
+ LET MAX_SPEED# = 5
880
+
881
+ SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
882
+
883
+ LET x$ = 320
884
+ LET y$ = 240
885
+ LET running$ = TRUE
886
+
887
+ ' ---- 3. MAIN LOOP ----
888
+ [main]
889
+ WHILE running$
890
+ IF INKEY = KEY_ESC# THEN running$ = FALSE
891
+ GOSUB [sub:update]
892
+ GOSUB [sub:draw]
893
+ SLEEP 16
894
+ WEND
895
+ SOUNDSTOPALL
896
+ END ' place at the end of main program so BazzBasic wont fall to subs in runtime
897
+
898
+ ' ---- 4. SUBROUTINES (or INCLUDE "subs.bas") ----
899
+ [sub:update]
900
+ IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
901
+ IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
902
+ RETURN
903
+
904
+ [sub:draw]
905
+ SCREENLOCK ON
906
+ LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
907
+ CIRCLE (x$, y$), 10, RGB(0, 255, 0), 1
908
+ SCREENLOCK OFF
909
+ RETURN
910
+ ```
911
+
912
+ **Key conventions:**
913
+ - Variables: `camelCase$` | Constants: `UPPER_SNAKE_CASE#` | Functions: `PascalCase$`
914
+ - Labels: `[gameLoop]` for jump targets, `[sub:name]` for subroutines
915
+ - Image/sound/shape IDs are stable integer handles — **always** store as constants: `LET MY_IMG# = LOADIMAGE("x.png")` — never use `$` variables for these
916
+ - Group many IDs → use arrays: `DIM sprites$` / `sprites$("player") = LOADIMAGE(...)` — but prefer named constants when count is small
917
+
918
+ ---
919
+
920
+ ## Performance Tips
921
+
922
+ - `LINE (0,0)-(W,H), 0, BF` to clear — much faster than `CLS`
923
+ - Always wrap draw code in `SCREENLOCK ON` / `SCREENLOCK OFF`
924
+ - Store `RGB()` results in constants/variables — don't call RGB in hot loops
925
+ - Declare all variables in `[inits]`, not inside loops or subroutines
926
+ - Use `FastTrig` for any loop calling trig hundreds of times per frame
927
+ - `SLEEP 16` in game loop → ~60 FPS
928
+
929
+ ---
930
+
931
+ ## Known Limitations
932
+
933
+ Things to be aware of — most are deliberate design decisions, a few are practical constraints.
934
+
935
+ - **Platform: Windows x64 only.** Linux and macOS are not supported. Browser/Android are not feasible — the runtime depends on SDL2 via P/Invoke.
936
+ - **Arrays cannot be passed to functions.** Use the `ASJSON` / `ASARRAY` round-trip pattern. The function receives an independent copy.
937
+ - **`DEF FN` scope is fully isolated.** Functions can read global `#` constants but cannot see any `$` variables from the outer scope. Pass values as parameters.
938
+ - **No block scope.** `IF`, `FOR`, and `WHILE` do not create new variable scopes — all main-code variables share one namespace.
939
+ - **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.
940
+ - **Division by zero returns `0` silently.** No exception, no warning. Guard with `IF b$ = 0 THEN ...` when correctness matters.
941
+ - **No integer-division operator.** Use `INT(a / b)`, `FLOOR(a / b)`, or `CINT(a / b)` depending on the rounding behavior you need.
942
+ - **Compiled `.bb` libraries are version-locked** to the BazzBasic build that produced them. Recompile after upgrading the interpreter.
943
+ - **`DEF FN` definitions must precede their first call** in source order. Forward references don't resolve.
944
+
945
+ ---
946
+
947
+ ## IDE Features (v1.4b)
948
+
949
+ ### New File Template
950
+ When the IDE opens with no file (or a new file), this template is auto-inserted:
951
+ ```basic
952
+ ' BazzBasic version {ver_num}
953
+ ' https://ekbass.github.io/BazzBasic/
954
+ ```
955
+
956
+ ### Beginner's Guide
957
+ - **IDE:** Menu → **Help** → **Beginner's Guide** — opens `https://github.com/EkBass/BazzBasic-Beginners-Guide/releases` in default browser
958
+ - **CLI:** `bazzbasic.exe -guide` or `bazzbasic.exe -help` — prints URL to terminal
959
+
960
+ ### Check for Updates
961
+ - **IDE:** Menu → **Help** → **Check for updated...** — IDE reports if a newer version is available
962
+ - **CLI:** `bazzbasic.exe -checkupdate`
963
+
964
+ ### Compile via IDE
965
+ - **Menu → Run → Compile as Exe** — compiles open file to standalone `.exe` (auto-saves first)
966
+ - **Menu → Run → Compile as Library (.bb)** — compiles open file as reusable `.bb` library (auto-saves first)
967
+
968
+ EOF