File size: 46,478 Bytes
688d8d3 5ac9a6d 688d8d3 2658093 688d8d3 5ac9a6d 688d8d3 5ac9a6d 688d8d3 cde1597 2658093 688d8d3 2658093 688d8d3 cde1597 5ac9a6d 688d8d3 5ac9a6d cde1597 688d8d3 5ac9a6d 688d8d3 cde1597 688d8d3 5ac9a6d cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 5ac9a6d 688d8d3 2658093 cde1597 a657d21 cde1597 5ac9a6d cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 2658093 cde1597 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 688d8d3 cde1597 2658093 cde1597 2658093 5ac9a6d cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 5ac9a6d cde1597 5ac9a6d cde1597 5ac9a6d cde1597 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 5ac9a6d 688d8d3 2658093 688d8d3 cde1597 2658093 cde1597 2658093 688d8d3 2658093 cde1597 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 688d8d3 cde1597 394fcd0 5ac9a6d cde1597 2658093 5ac9a6d 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 5ac9a6d 688d8d3 2658093 5ac9a6d 688d8d3 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 5ac9a6d 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 688d8d3 cde1597 688d8d3 cde1597 688d8d3 2658093 cde1597 394fcd0 cde1597 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 394fcd0 cde1597 5ac9a6d cde1597 688d8d3 cde1597 2658093 cde1597 688d8d3 2658093 cde1597 688d8d3 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 688d8d3 2658093 cde1597 688d8d3 cde1597 688d8d3 cde1597 688d8d3 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 5ac9a6d 688d8d3 5ac9a6d 688d8d3 5ac9a6d 688d8d3 5ac9a6d 688d8d3 5ac9a6d cde1597 5ac9a6d 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 688d8d3 cde1597 394fcd0 cde1597 2658093 cde1597 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 688d8d3 5ac9a6d 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 cde1597 a657d21 cde1597 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 5ac9a6d cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 2658093 688d8d3 cde1597 2658093 cde1597 688d8d3 2658093 cde1597 2658093 cde1597 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 5ac9a6d 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 688d8d3 2658093 cde1597 688d8d3 2658093 5ac9a6d 688d8d3 2658093 5ac9a6d 2658093 688d8d3 cde1597 5ac9a6d cde1597 688d8d3 2658093 cde1597 5ac9a6d cde1597 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 5ac9a6d 2658093 cde1597 2658093 688d8d3 cde1597 688d8d3 cde1597 394fcd0 2658093 5ac9a6d cde1597 a657d21 cde1597 2658093 394fcd0 cde1597 2658093 cde1597 394fcd0 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 2658093 688d8d3 cde1597 2658093 cde1597 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 5ac9a6d 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 2658093 cde1597 5ac9a6d 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 688d8d3 cde1597 2658093 688d8d3 2658093 688d8d3 2658093 688d8d3 cde1597 688d8d3 cde1597 2658093 cde1597 688d8d3 2658093 688d8d3 cde1597 688d8d3 2658093 cde1597 394fcd0 cde1597 394fcd0 cde1597 2658093 688d8d3 cde1597 394fcd0 cde1597 394fcd0 cde1597 5ac9a6d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 | ---
name: "bazzbasic-code"
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."
---
# BazzBasic Language Reference
**Version:** 1.7 | **Author:** Kristian Virtanen (EkBass) | **Platform:** Windows x64 only (SDL2 via P/Invoke — no Linux, macOS, browser or Android)
**Homepage:** https://ekbass.github.io/BazzBasic/
**GitHub:** https://github.com/EkBass/BazzBasic
**Manual:** https://ekbass.github.io/BazzBasic/manual/#/
**Examples:** https://github.com/EkBass/BazzBasic/tree/main/Examples
**Rosetta Code:** https://rosettacode.org/wiki/Category:BazzBasic
**Rosetta Code solutions:** https://github.com/EkBass/BazzBasic/tree/main/Examples/rosetta-code
**BazzBasic-AI-Guide:** https://huggingface.co/datasets/EkBass/BazzBasic_AI_Guide
**BazzBasic Beginner's Guide:** https://github.com/EkBass/BazzBasic-Beginners-Guide/releases
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.
---
## ⚠️ Critical Rules — Read First
| Rule | Detail |
|------|--------|
| Variables end with `$` | `name$`, `score$`, `x$` — the suffix does NOT mean string type |
| Constants end with `#` | `MAX#`, `PI#`, `TITLE#` — `#` only means immutable |
| Built-in constants cannot be redefined | `LET PI# = 3.14` is an error (`Cannot redefine constant 'PI#'`) — use your own name: `LET MY_PI# = 3.14` |
| Arrays declared with `DIM`, end with `$` | `DIM items$`. A non-`$` name (`DIM MAX#`) is an error. `DIM` ends at `:`, so `DIM a$ : a$(0) = 1` works |
| First use of variable requires `LET` | `LET x$ = 0` — after that `x$ = x$ + 1` |
| FOR and INPUT auto-declare, no LET needed | `FOR i$ = 1 TO 10` |
| Case-insensitive | Keywords, variables, constants, labels and array names. For text values see the next row |
| Case rules differ for text | `=` `<>` `<` `>` `<=` `>=` ignore case: `"abc" = "ABC"` → `1`. Array string keys are case-sensitive (`arr$("name")` and `arr$("NAME")` are different elements), and so is `INSTR` by default. JSON object keys are too, in both directions: `ASJSON`/`SAVEJSON` write them verbatim, `ASARRAY`/`LOADJSON` read them verbatim. Exact (case-sensitive) compare: `IF SAME(pass$, input$) THEN`. Before 1.7 (no `SAME`): `LEN(a$) = LEN(b$) AND INSTR(a$ + "~", b$ + "~") = 1` — the `+ "~"` makes two empty strings match |
| Functions defined **before** they are called | Put at top or INCLUDE — forward references don't resolve |
| Function name ends with `$`, called with `FN` | `FN MyFunc$(a$, b$)` |
| Parameters end with `$`; pass exactly as many arguments as defined | `DEF FN F$(a$, B#)` is an error (`#` = constant). `FN Add$(1)` for `Add$(a$, b$)` stops with `FN ADD$: expected 2 arguments, got 1` |
| Function return value **must** be used | `PRINT FN f$()` or `LET v$ = FN f$()` |
| `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* |
| `+` does both add and concatenate | If either side is a string, the other is auto-converted: `"Score: " + 5` → `"Score: 5"`, no `STR()` needed |
| Division always returns float | `10 / 3` → `3.333...` |
| Division by zero returns `0` silently | Same for `/`, `/=`, `%` and `MOD(a, 0)`. Guard with `IF b$ = 0 THEN ...` if correctness matters |
| No `\` or `^` operator | Both are an error before the program runs (`Unexpected character '\'`). Integer division: `INT(a / b)`, `FLOOR(a / b)` or `CINT(a / b)`; power: `POW(a, b)` |
| Errors halt the program | No `TRY`/`CATCH` or `ON ERROR` — line-numbered message printed. Exception: a failed `HTTPGET`/`HTTPPOST` returns `""` and sets `HTTPERROR` (see *Network*) |
| No line-continuation char | Leave an operator at line end or open a `(` — see *Line Continuation* |
| No line numbers | Never supported. Use `[labels]` |
| `:` 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 |
| `NOT` binds tighter than comparisons | `NOT a$ = b$` means `(NOT a$) = b$`. Parenthesize: `IF NOT (a$ = b$) THEN`, or use `<>` |
| Comments: `'` or `REM` | `' comment` anywhere on a line; `REM` as a statement, also after `:` (`PRINT x$ : REM note`) |
---
## 🚫 Common AI Mistakes (avoid these)
These are the patterns LLMs most often produce when extrapolating from QBASIC, FreeBASIC, or VB. None of them are valid BazzBasic.
```basic
' ❌ WRONG ' ✓ CORRECT
LET x = 5 LET x$ = 5
LET MAX = 10 LET MAX# = 10
score$ = 0 ' first use LET score$ = 0
DEF FN doStuff(a, b) DEF FN DoStuff$(a$, b$)
FN MyFunc$(5) ' return ignored LET v$ = FN MyFunc$(5)
LET handle$ = LOADIMAGE("x.png") LET HANDLE# = LOADIMAGE("x.png")
CLS ' in graphics mode LINE (0,0)-(W,H), 0, BF
PRINT "x:", x$ ' in graphics mode DRAWSTRING "x:" + x$, 10, 10, WHITE#
FSTRING("Hi {{name$}}") ' Python-style FSTRING("Hi {{-name$-}}") ' triple-char markers
ISSET(arr$(0)) ' expecting error ' returns 0 silently — ISSET only sees scalars
LET x$ = a$ + _ ' VBA continuation LET x$ = a$ + ' just leave the operator
LET x$ = a$ + \ ' Python continuation LET x$ = a$ + ' or open a paren
IF NOT a$ = b$ THEN ' QBASIC habit IF NOT (a$ = b$) THEN
IF done$ THEN BREAK ' C/Python habit IF done$ THEN EXIT WHILE ' or EXIT FOR
IF done$ THEN GOTO [after] ' out of loop IF done$ THEN EXIT FOR ' GOTO leaks loop state
```
---
## When Generating BazzBasic Code
- Prefer `FSTRING` over long `+` concatenation chains for multi-variable strings
- Place `DEF FN` definitions at the top of the file or via `INCLUDE`
- Store every `LOADIMAGE` / `LOADSOUND` / `LOADSHAPE` handle as a `#` constant. They return string handles that never change while the program runs — images/shapes (also each `LOADSHEET` cell) `"SHAPE1"`, `"SHAPE2"`…, sounds a GUID-style string like `"57212810-1166-4bcf-8ccd-bdfc6607046f"`. Treat them as opaque IDs, not numbers. For many handles, an array is fine: `sprites$("player") = LOADIMAGE(...)`
- Declare all variables and constants in `[inits]`, not inside loops — this avoids repeated existence checks
- Precompute colors: `LET WHITE# = RGB(255, 255, 255)` in `[inits]`, never `RGB()` inside a game loop
- 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`
- 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
---
## Minimal Valid Program
```basic
[inits] ' [name] is a plain jump label, not a keyword
LET name$ = "World"
[main]
PRINT "Hello, " + name$
END
' subroutines go after END
[sub:drawScreen]
' draw
RETURN
```
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.
---
## Line Continuation
The lexer figures out continuation automatically using two rules. Never emit `_`, `\`, `&` or any other continuation marker.
**Rule 1 — operator at end of line.** If a line ends in a token that cannot legally end an expression, the next line continues it:
```basic
LET total$ = price$ * count$ -
discount$
IF score$ >= 0 AND
score$ <= 100 THEN
PRINT "Valid"
END IF
LET counter$ +=
step$
```
Tokens that trigger this: `+ - * / % = <> < <= > >= AND OR += -= *= /= ,`
> `%` 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).
**Rule 2 — open paren.** Anything inside an unmatched `(` keeps reading until the matching `)`:
```basic
LET dist$ = DISTANCE(
x1$, y1$,
x2$, y2$
)
```
---
## Variables & Constants
Variables are dynamically typed, like in JavaScript.
```basic
LET a$ ' Declare without value
LET b$, c$, d$ ' Multiple declarations without value
LET e$, f$ = "foo", g$ = 10 ' e$ stays empty, f$ and g$ get values
LET name$ = "Alice" ' String
LET score$ = 0 ' Number
LET MAX_LIVES# = 3 ' Constant (immutable)
LET TITLE# = "My Game" ' String constant
```
**Compound assignment** (variables only — **not** allowed with `#` constants):
```basic
LET x$ = 1
x$ += 5
x$ -= 3
x$ *= 2
x$ /= 4
LET s$ = "Hello"
s$ += " World" ' concatenation
```
**Scope:** All main-code variables share one scope — `IF`, `FOR`, and `WHILE` do NOT create a new scope.
**Comparison:** `"123" = 123` is TRUE (cross-type), but keep types consistent for speed.
### Built-in Constants
- **Boolean:** `TRUE` & `ON` (`1`), `FALSE` & `OFF` (`0`) — plain numbers. `IF x$ = 1` and `IF x$ = TRUE` are identical.
- **Math:** `PI#`, `HPI#` (π/2 = 90°), `QPI#` (π/4 = 45°), `TAU#` (2π = 360°), `EULER#` (e)
- **Astronomy:** `AU#` = 149597870700 — astronomical unit in metres (exact, IAU 2012)
- **System:** `PRG_ROOT#` (program base directory path, ends with a separator)
- **Version:** `BBVER#` (current BazzBasic version as a string, e.g. `"1.7"`), `BBBUILD#` (interpreter build time as a string `"dd-mm-yyyy hh:mm:ss"`, e.g. `"06-11-2026 20:47:16"`; an `-exe` program reports the build time of the interpreter it was made with, since 1.7)
- **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#`, punctuation (layout-dependent) `KEY_COMMA#` `KEY_DOT#` `KEY_MINUS#` `KEY_EQUALS#` `KEY_SLASH#` `KEY_BACKSLASH#` `KEY_SEP#` (`;`) `KEY_GRAVE#` `KEY_LBRACKET#` `KEY_RBRACKET#` — see *Keyboard Input*
- **Gamepad:** see *Gamepad*
---
## Arrays
Arrays are fully dynamic and support numeric, string, or mixed indexing.
```basic
DIM scores$ ' Declare (required before use)
DIM a$, b$, c$ ' Multiple
scores$(0) = 95 ' Numeric indices are 0-based
scores$("name") = "Alice" ' String keys: associative, insertion-ordered
PRINT HASKEY(scores$("NAME")) ' 0 - string keys are case-sensitive; use UCASE(key$) to normalize
matrix$(0, 1) = "A2" ' Multi-dimensional
DIM sounds$
sounds$("guns", "shotgun_shoot") = "shoot_shotgun.wav"
sounds$("guns", "ak47_shoot") = "shoot_ak47.wav"
sounds$("food", "ham_eat") = "eat_ham.wav"
PRINT LEN(sounds$()) ' 3 - total elements across all groups
PRINT ROWCOUNT(sounds$()) ' 2 - "guns" & "food"
DIM car$
car$("manufacturer") = "Ford"
car$("engine") = "1.6 Eco"
FOR i$ = 0 TO LEN(car$()) - 1 ' No FOREACH — LEN + ARRKEY is the idiom
LET key$ = ARRKEY(car$(), i$)
PRINT key$; " = "; car$(key$)
NEXT i$
```
| Function/Command | Description |
|-----------------|-------------|
| `LEN(arr$())` | Total element count across all dimensions |
| `ROWCOUNT(arr$())` | Count of first-dimension rows — use this for FOR loops over multi-dim arrays |
| `ARRKEY(arr$(), i)` | Key at 0-based index `i`, in insertion order. Errors on out-of-range index |
| `HASKEY(arr$(key))` | 1 if exists, 0 if not — **always check before reading possibly uninitialized elements** |
| `DELKEY arr$(key)` | Remove one element |
| `DELARRAY arr$` | Remove entire array (can re-DIM after) |
| `JOIN dest$, src1$, src2$` | Merge two arrays; matching `src2$` keys overwrite `src1$` at the same level. Use an empty `src1$` to copy an array |
> Re-DIM of an existing global array is a no-op (contents kept) — only `DELARRAY` removes it. Inside `DEF FN`, `DIM` always creates a fresh local array.
> `DIM arr$ = value` stores the value at `arr$(0)` — NOT as a scalar. If a scalar is what you want, use `LET`.
> `DIM arr$(10)` is accepted but the size is ignored — it declares the same empty dynamic array as `DIM arr$`; nothing inside the parentheses is read. Write plain `DIM arr$`. Size and value cannot be combined: `DIM arr$(10) = 5` is an error.
---
## Control Flow
```basic
' Block IF
IF score$ >= 90 THEN
PRINT "A"
ELSEIF score$ >= 80 THEN
PRINT "B"
ELSE
PRINT "F"
END IF ' ENDIF also works
' One-line IF
IF lives$ = 0 THEN GOTO [game_over]
IF key$ = KEY_ESC# THEN GOTO [menu] ELSE GOTO [play]
' FOR (auto-declares variable)
FOR i$ = 1 TO 10 STEP 2 : PRINT i$ : NEXT
FOR i$ = 10 TO 1 STEP -1 : PRINT i$ : NEXT
' End value of counter Comparison. Wont pass ending point like in MS-BASIC style dialects
FOR i$ = 1 TO 10 : NEXT : PRINT i$ ' 10
FOR i$ = 1 TO 10 STEP 4 : NEXT : PRINT i$ ' 9
' EXIT FOR — leave innermost FOR, continue after its NEXT (loop var keeps its value)
FOR i$ = 1 TO 100
IF i$ * i$ > 50 THEN EXIT FOR
NEXT
PRINT "First square over 50: "; i$ ' 8
' WHILE
WHILE x$ < 100
x$ = x$ * 2
WEND
' EXIT WHILE — leave innermost WHILE, continue after its WEND
LET key$
WHILE 1
key$ = INKEY
IF key$ = KEY_ESC# THEN EXIT WHILE
' Game logic here
WEND
PRINT "Goodbye"
' Labels, GOTO, GOSUB
[start]
GOSUB [sub:init]
GOTO [start] ' Avoid jumping into the middle of IF/WHILE blocks
[sub:init]
LET x$ = 0
RETURN
' Dynamic jump (variable must contain "[label]" with brackets)
LET target$ = "[menu]"
GOTO target$
SLEEP 2000 ' Pause for milliseconds
END ' Terminate program
```
Labels may contain almost any printable character. Whitespace is trimmed; everything between `[` and `]` is the label name.
### EXIT FOR / EXIT WHILE (since 1.5)
- Work anywhere inside the loop: one-line IF, inside an `IF...END IF` block, or inside an inner loop of the *other* kind. `EXIT WHILE` inside a FOR that sits in a WHILE leaves both loops.
- Only the innermost loop of the named kind is left. To leave several nested loops of the same kind at once, use a flag variable.
- Inside `DEF FN`, EXIT can only leave loops that are inside the function.
- `EXIT` without a loop of that kind is an error: `EXIT WHILE without WHILE`.
- Prefer EXIT over `GOTO` out of a loop. A GOTO leaves the loop's bookkeeping behind; doing it repeatedly (e.g. once per frame) slowly fills memory and can confuse later `NEXT` statements.
---
## I/O
| Command | Description |
|---------|-------------|
| `PRINT expr; expr` | `;` = no space, `,` = tab, can be mixed |
| `PRINT "text";` | Trailing `;` suppresses newline |
| `INPUT "prompt", var$` | Splits on whitespace/comma; quoted strings are single values |
| `INPUT "prompt", a$, b$` | Multiple values |
| `LINE INPUT "prompt", var$` | Read entire line with spaces |
| `CLS` | Clear screen (console) |
| `LOCATE row, col` | Move cursor (1-based) |
| `CURPOS("row")` / `CURPOS("col")` | Read cursor row or col (1-based, matches LOCATE) |
| `CURPOS()` | Read cursor as `"row,col"` string |
| `COLOR fg, bg` | Text colors, palette 0–15 only (`RGB()` does not work here) |
| `GETCONSOLE(row, col, type)` | Read console cell. type: 0=char (ASCII), 1=fg color, 2=bg color |
| `SHELL("cmd")` | Run shell command, returns output |
| `SHELL("cmd", ms)` | With timeout in ms (default 5000) |
**Escape sequences in strings:** `\"` `\n` `\t` `\\` `""`
**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:
- Always append `2>&1`, or SQL errors disappear silently.
- Wrap the SQL with `\"`: `SHELL("sqlite3 db.sqlite \"SELECT * FROM users\" 2>&1")`.
- In paths use `/` or `\\` — never a single `\`.
### Keyboard Input
| Function | Returns | Notes |
|----------|---------|-------|
| `INKEY` | Key value or 0 | Non-blocking |
| `KEYDOWN(key#)` | TRUE/FALSE | Held-key detection, graphics mode only |
| `WAITKEY(key#, ...)` | Key value | Blocks until key pressed; `WAITKEY()` = any key |
- **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#`.
- Letters always return uppercase codes (`"a"` and `"A"` → `KEY_A#`), in both graphics and console mode.
- `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.
- Numpad Enter = `KEY_ENTER#`.
- `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.
- Console mode: `INKEY`/`WAITKEY` return the typed character (except letters and special keys); numpad returns the typed digit, not `KEY_NUMPAD*#`.
- No real console (redirected stdin/stdout): console `INKEY`/`WAITKEY`/`SLEEP`/`CLS`/`CURPOS` stop with a line-numbered `Error at line N: ...` and exit code 1; piped `INPUT`/`LINE INPUT` still works.
### Mouse (graphics mode only)
`MOUSEX`, `MOUSEY` — cursor position
`MOUSELEFT`, `MOUSERIGHT`, `MOUSEMIDDLE` — 1 if pressed, 0 otherwise
`MOUSEHIDE` / `MOUSESHOW` — hide / restore the cursor
### Gamepad (console AND graphics mode)
| Function | Returns | Notes |
|----------|---------|-------|
| `GAMEPADS()` | Number of connected pads | Parentheses optional |
| `PADBUTTON(pad, button)` | TRUE/FALSE | TRUE while held (like `KEYDOWN`) |
| `PADAXIS(pad, axis)` | Number | Sticks -1.0…1.0, triggers 0.0…1.0, built-in dead zone |
| `PADNAME(pad)` | String | e.g. `"PS4 Controller"`, `""` if not connected |
| `PADRUMBLE pad, strength, ms` | — (statement) | strength 0.0…1.0, non-blocking, parentheses optional |
- Pad index is **0-based**, max 8 pads. Slots are stable while connected (not re-packed on disconnect). Hot-plug works.
- **No `SCREEN` needed** — works in console programs too.
- **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.
- 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.
- Axes: `PAD_LX#` `PAD_LY#` `PAD_RX#` `PAD_RY#` `PAD_LT#` `PAD_RT#`. Raw 0–5; outside → error.
- **Y axis: negative = up**, same as screen Y. `y$ = y$ + PADAXIS(0, PAD_LY#) * SPEED#` is correct — do not invert.
- **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#`).
- For one action per press, keep previous state: `IF now$ = TRUE AND was$ = FALSE THEN ...` then `was$ = now$`.
- Stick as digital direction: `IF PADAXIS(0, PAD_LX#) < -0.5 THEN ...`
- Pad OR keyboard: `IF PADBUTTON(0, PAD_LEFT#) OR KEYDOWN(KEY_LEFT#) THEN dx$ = -1`
- Many third-party pads identify as PS4/Xbox controllers — normal, mapping is still correct.
---
## User-Defined Functions
```basic
DEF FN Clamp$(val$, lo$, hi$)
IF val$ < lo$ THEN RETURN lo$
IF val$ > hi$ THEN RETURN hi$
RETURN val$
END DEF
PRINT FN Clamp$(5, 1, 10) ' ✓ return value used
LET v$ = FN Clamp$(15, 0, 10) ' ✓
FN Clamp$(5, 1, 10) ' ✗ ERROR — return value unused
```
- 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()`
- `DIM` inside a function creates a **fresh, empty, local** array on every call and every recursion level:
```basic
DEF FN Count$(x$)
DIM t$
t$(x$) = 1
RETURN LEN(t$())
END DEF
PRINT FN Count$(1) ' 1
PRINT FN Count$(2) ' 1 (not 2)
```
- Parameters are passed **by value**
- Labels inside functions are local — GOTO/GOSUB cannot jump outside
- 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.
---
## String Functions
| Function | Description |
|----------|-------------|
| `ASC(s$)` | ASCII code of first char |
| `ASC(s$, pos)` | ASCII code of char at 1-based `pos`; out of range (`pos < 1` or `pos > LEN(s$)`) → `0`. Prefer over `ASC(MID(s$, pos, 1))` in loops (no temp substring, ~35 % faster) |
| `CHR(n)` | Character from ASCII code |
| `INSTR(s$, search$)` | Position (1-based), 0=not found; case-sensitive. Start form `INSTR(start, s$, search$)`: `start` < 1 or > `LEN(s$)` → `0` |
| `INSTR(s$, search$, mode)` | mode: 0=case-insensitive, 1=case-sensitive |
| `INVERT(s$)` | Reverse string |
| `LCASE(s$)` / `UCASE(s$)` | Lower / upper case |
| `LEFT(s$, n)` / `RIGHT(s$, n)` | First/last n chars; `n <= 0` → `""`, `n >= LEN(s$)` → whole string |
| `LEN(s$)` | String length |
| `LTRIM(s$)` / `RTRIM(s$)` / `TRIM(s$)` | Strip whitespace |
| `MID(s$, start)` | Substring from start (1-based); `start` < 1 or > `LEN(s$)` → `""` |
| `MID(s$, start, len)` | Substring with length; `len` < 0 → runtime error (`MID: length must be 0 or more, got -1`); `len` past the end clamps to the tail |
| `REPEAT(s$, n)` | Repeat n times; `n <= 0` or empty string → `""`; result > 2147483647 chars → runtime error (`REPEAT: result too large (N characters)`) |
| `REPLACE(s$, a$, b$)` | Replace a$ with b$ in s$ |
| `SAME(a$, b$)` | 1 if identical, case-sensitive (`SAME("A", "a")` → `0`); numbers compare as text (`SAME("1.0", 1)` → `0`) — use `=` for numbers. Since 1.7 |
| `SPLIT(arr$, s$, sep$)` | Split into array (keys `0`..`count-1`), returns count. Array is emptied first. `arr$()` also accepted |
| `SRAND(n)` | Random alphanumeric string of length n (decimals dropped). `n = 0` → `""`; a negative n is a runtime error (`SRAND: length must be 0 or more, got -1`) |
| `STR(n)` | Number to string |
| `VAL(s$)` | String to number |
| `SHA256(s$)` | SHA256 hash (64-char hex) |
| `BASE64ENCODE(s$)` / `BASE64DECODE(s$)` | Base64 encode/decode |
---
## FSTRING — String Interpolation
`FSTRING(template$)` substitutes `{{-name-}}` placeholders with the value of variables, constants, or array elements.
```basic
LET name$ = "Krisu"
LET LEVEL# = 5
PRINT FSTRING("Hello {{-name$-}}, level {{-LEVEL#-}}")
' Output: Hello Krisu, level 5
```
The triple-character markers `{{-` and `-}}` are deliberately unusual. There is no escape syntax — literal `{{-...-}}` is always parsed as a placeholder.
| Form | Resolves to |
|------|-------------|
| `{{-var$-}}` | Variable `var$` |
| `{{-CONST#-}}` | Constant `CONST#` (built-ins like `{{-PI#-}}` work too) |
| `{{-arr$(0)-}}` | Element at numeric index `0` |
| `{{-arr$(i$)-}}` | Element at index from variable `i$` |
| `{{-arr$(KEY#)-}}` | Element at index from constant `KEY#` |
| `{{-arr$(name)-}}` | Element at literal string key `"name"` (no quotes inside FSTRING) |
| `{{-arr$(0, i$)-}}` | Multidimensional, mixed literal and variable indices |
**Index resolution** — for each comma-separated index, FSTRING checks:
1. Ends with `$` or `#` → variable / constant lookup. Halts if undefined.
2. Parses as a number → numeric index. `arr$(01)` and `arr$(1.0)` both resolve to key `1`.
3. Otherwise → literal string key.
So `{{-name-}}` (no suffix) is a literal array key, **not** variable `name$`. Always include the suffix.
**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.
**Not supported:** arithmetic, function calls, nested lookups, or quoted literals inside placeholders. Pre-compute into a variable:
```basic
' ❌ WRONG
PRINT FSTRING("Total: {{-a$ + 5-}}")
PRINT FSTRING("Name: {{-UCASE(name$)-}}")
PRINT FSTRING("{{-arr$(arr2$(0))-}}")
' ✓ RIGHT
LET total$ = a$ + 5
LET upper$ = UCASE(name$)
LET k$ = arr2$(0)
PRINT FSTRING("Total: {{-total$-}}, Name: {{-upper$-}}, Item: {{-arr$(k$)-}}")
```
**Full example:**
```basic
DIM player$
player$("name") = "Krisu"
player$("class") = "Bass"
player$("level") = 99
DIM grid$
grid$(1, 0) = "."
grid$(1, 1) = "X"
LET row$ = 1
PRINT FSTRING("{{-player$(name)-}} the {{-player$(class)-}}, lvl {{-player$(level)-}}")
PRINT FSTRING("Row {{-row$-}}: [{{-grid$(row$, 0)-}}{{-grid$(row$, 1)-}}]")
END
' Output:
' Krisu the Bass, lvl 99
' Row 1: [.X]
```
---
## Math Functions
| Function | Description |
|----------|-------------|
| `ABS(n)` | Absolute value |
| `ATAN(n)` | Arc tangent |
| `ATAN2(y, x)` | Angle in radians from the positive x-axis to point (x, y) |
| `BETWEEN(n, min, max)` | TRUE if min ≤ n ≤ max |
| `INBETWEEN(n, min, max)` | TRUE if min < n < max (strict) |
| `CEIL(n)` / `FLOOR(n)` | Round up / down |
| `CINT(n)` | Round to nearest integer |
| `CLAMP(n, min, max)` | Constrain n to [min, max] |
| `COS(n)` / `SIN(n)` / `TAN(n)` | Trig (radians) |
| `DEG(rad)` / `RAD(deg)` | Radians ↔ degrees |
| `DISTANCE(x1,y1, x2,y2)` | 2D Euclidean distance |
| `DISTANCE(x1,y1,z1, x2,y2,z2)` | 3D Euclidean distance |
| `EXP(n)` | e^n |
| `INT(n)` | Truncate toward zero |
| `LERP(start, end, t)` | Linear interpolation (t: 0.0–1.0) |
| `LOG(n)` | Natural logarithm |
| `MAX(a, b)` / `MIN(a, b)` | Larger / smaller of two |
| `MOD(a, b)` / `a % b` | Remainder (function and operator forms are equivalent). `b = 0` → `0` |
| `POW(base, exp)` | Power |
| `RND(n)` | Random integer 0 to n-1 (n > 0) |
| `RND(0)` | Random float 0.0–1.0 |
| `ROUND(n)` | Nearest integer, half away from zero (`0.5→1`, `-0.5→-1`) — NOT banker's rounding |
| `SGN(n)` | Sign: -1, 0, or 1 |
| `SQR(n)` | Square root |
### Fast Trigonometry
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.
```basic
FastTrig(TRUE) ' Enable lookup tables (must call first)
LET x$ = FastCos(45) ' Degrees, auto-normalized 0–359
LET y$ = FastSin(90)
LET r$ = FastRad(180) ' Deg→rad (no FastTrig needed)
FastTrig(FALSE) ' Free memory
```
---
## ISSET
`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`.
- **Scalars only.** `ISSET(arr$)` and `ISSET(arr$(0))` always return `0`, never an error.
- **Bare name only.** Expressions, string literals, numbers or an empty argument (`ISSET(a$ + b$)`, `ISSET("a$")`, `ISSET(42)`, `ISSET()`) error with "invalid parameter".
- **Suffix is part of the name:** `a$` and `A#` are different names.
- **`LET name$` without a value still counts as set.** ISSET reports declaration, not "has a meaningful value".
```basic
IF ISSET(playerName$) = FALSE THEN
LET playerName$ = "Anonymous"
END IF
```
---
## Graphics
```basic
SCREEN 12 ' 640×480 VGA
SCREEN 0, 800, 600 ' Custom size
SCREEN 0, 1024, 768, "My Game" ' Custom size + title
FULLSCREEN TRUE ' Borderless fullscreen (graphics only)
FULLSCREEN FALSE ' Windowed
```
Classic modes: 1, 7, 13 = 320×200 · 2, 9 = 640×350 · 12 = 640×480.
### Drawing Primitives
```basic
PSET (x, y), color ' Pixel
LINE (x1,y1)-(x2,y2), color ' Line
LINE (x1,y1)-(x2,y2), color, B ' Box outline
LINE (x1,y1)-(x2,y2), color, BF ' Box filled
CIRCLE (cx,cy), radius, color ' Circle outline
CIRCLE (cx,cy), radius, color, 1 ' Circle filled
PAINT (x, y), fillColor, borderColor ' Flood fill
LET c$ = POINT(x, y) ' Read pixel color
SAVESCREEN "shot.png" ' Save screen as PNG (only .png; relative to program folder)
LET COL# = RGB(r, g, b) ' Create color (0–255 each)
```
**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.
**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
### Screen Control
```basic
SCREENLOCK ON ' Start frame (buffer drawing)
SCREENLOCK OFF ' Present buffer
VSYNC(TRUE) ' Enable VSync (default) — loop runs at monitor refresh rate
VSYNC(FALSE) ' Disable VSync (benchmarking)
```
### Shapes & Images
```basic
LET RECT# = LOADSHAPE("RECTANGLE", w, h, color) ' or "CIRCLE", "TRIANGLE"
LET IMG_PLAYER# = LOADIMAGE("player.png") ' PNG (alpha) or BMP
LET IMG_REMOTE# = LOADIMAGE("https://example.com/a.png") ' Download + load
' Sprite sheet — sprites indexed 0-based
DIM sprites$
LOADSHEET sprites$, 128, 128, "sheet.png" ' tileW, tileH, file
MOVESHAPE sprites$(0), x, y
MOVESHAPE RECT#, x, y ' Position
ROTATESHAPE RECT#, angle ' Degrees (absolute)
SCALESHAPE RECT#, scale ' 1.0 = original size
DRAWSHAPE RECT# ' Render to buffer
SHOWSHAPE RECT# / HIDESHAPE RECT# ' Toggle visibility
REMOVESHAPE RECT# ' Free memory (always clean up)
```
**Anchor point:** `LOADSHAPE` primitives are center-anchored; `LOADIMAGE` images are top-left-anchored.
### Text Rendering (requires SDL2_ttf.dll next to the interpreter)
```basic
DRAWSTRING "Hello!", 100, 200, WHITE# ' Default font: Arial, 16px
LOADFONT "comic.ttf", 24 ' Becomes the new default
LOADFONT ' Reset to Arial 16px
```
`DRAWSTRING text, x, y, color` positions the top-left of the text.
---
## Sound
```basic
LET SND_JUMP# = LOADSOUND("jump.wav") ' Load (WAV recommended)
SOUNDONCE(SND_JUMP#) ' Play once, non-blocking
SOUNDONCEWAIT(SND_JUMP#) ' Play once, wait for finish
SOUNDREPEAT(SND_JUMP#) ' Loop continuously
SOUNDSTOP(SND_JUMP#) ' Stop specific sound
SOUNDSTOPALL ' Stop all sounds
```
Load all sounds at startup. Call `SOUNDSTOPALL` before `END`.
---
## File I/O
```basic
LET data$ = FILEREAD("file.txt") ' Read as string
DIM cfg$ : LET cfg$ = FILEREAD("settings.txt") ' Read as key=value array
FILEWRITE "save.txt", data$ ' Create/overwrite (array → key=value format)
FILEAPPEND "log.txt", entry$ ' Append
LET ok$ = FILEEXISTS("file.txt") ' 1=exists, 0=not
FILEDELETE "temp.dat" ' Delete file
DIM files$
LET n$ = FILELIST(files$, "levels", "*.txt") ' Names into files$(0..n-1), returns n
```
**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:
```basic
DIM env$
LET env$ = FILEREAD(".env")
LET API_KEY# = env$("OPENAI_API_KEY")
```
**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$))`.
**Paths:** Use `/` or `\\` — never a single `\` (escape char). Relative paths are from `PRG_ROOT#`, which already ends with a separator: `PRG_ROOT# + "data.txt"`. This also covers asset loads: `LOADIMAGE`, `LOADSHEET`, `LOADSOUND`, `LOADFONT` and `SAVESCREEN` resolve relative paths from the program folder too.
---
## Network
```basic
LET res$ = HTTPGET("https://api.example.com/data")
LET res$ = HTTPPOST("https://api.example.com/submit", "{""key"":""val""}")
' Optional headers
DIM headers$
headers$("Authorization") = "Bearer mytoken"
headers$("Content-Type") = "application/json"
LET res$ = HTTPGET("https://api.example.com/data", headers$)
LET res$ = HTTPPOST("https://api.example.com/data", body$, headers$)
' Optional timeout in seconds, AFTER headers (default 30, 0 = no limit)
LET res$ = HTTPPOST("http://localhost:11434/v1/chat/completions", body$, headers$, 120)
```
**Failed requests do not stop the program.** On connection error, unknown host or timeout, `HTTPGET`/`HTTPPOST` return `""` and `HTTPERROR` holds the reason (`""` after a successful call; parentheses optional). Check it right after the call:
```basic
LET res$ = HTTPGET(url$)
IF HTTPERROR <> "" THEN
PRINT "Source is down: "; HTTPERROR
ELSE
' use res$
END IF
```
- `HTTPERROR` has no `$` — it is a built-in function like `TICKS`, not a variable.
- An invalid URL (not `http://`/`https://`) is still a program-stopping error.
- HTTP error statuses (404, 500…) are **not** errors: the body (often an HTML error page) is returned and `HTTPERROR` is `""`.
- `""` alone does not prove failure — a server may answer with an empty body. Use `HTTPERROR` when it matters.
### Local HTTP server (LISTEN)
Small HTTP server, typically glue between a static HTML page and a BazzBasic script on the same machine.
```basic
STARTLISTEN 8080 ' Bind 127.0.0.1:8080, no admin needed
STARTLISTEN 8080, 5000 ' Optional timeout in ms (0 = wait forever)
STARTLISTEN 8080, 0, "*" ' Optional host: "*" = all network interfaces
LET body$ = GETREQUEST() ' POST/PUT/PATCH body or GET query string ("" on timeout)
SENDRESPONSE "{""status"":""ok""}" ' Must be called or the browser hangs
STOPLISTEN
```
- **Always pair `GETREQUEST()` with `SENDRESPONSE`.**
- **Default is `127.0.0.1`.** Use a host (`"*"` or an address) only when the user wants other computers to connect. Then tell them: Windows needs a one-time `netsh http add urlacl url=http://+:PORT/ user=Everyone` as administrator (STARTLISTEN's error prints the exact command), the firewall must allow the port, and the server is plain HTTP with no authentication or body size limit.
- **Host is positional:** it is the third argument, so pass a timeout first (`0` for none).
- **Body or query string only** (no `?`). Headers, method and URL path are not exposed. Parse JSON bodies with `ASARRAY`.
- **OPTIONS preflight and CORS are automatic.** Don't handle `OPTIONS`; every response carries `Access-Control-Allow-Origin: *`.
- **One listener at a time.** Call `STOPLISTEN` before another `STARTLISTEN`.
- **Always 200 OK, always `text/plain`.** To return JSON, put JSON text in the body — browser-side `response.json()` still works.
```basic
STARTLISTEN 8080
PRINT "Waiting for browser..."
LET json$ = GETREQUEST()
DIM data$
LET count$ = ASARRAY(data$, json$)
PRINT "Got name: " + data$("name")
SENDRESPONSE "{""status"":""ok""}"
STOPLISTEN
END
```
---
## Arrays & JSON (and XML)
Nested JSON maps to comma-separated keys: `data$("player,name")`, `data$("skills,0")`.
```basic
LET json$ = ASJSON(arr$) ' Array → JSON string
DIM data$
LET count$ = ASARRAY(data$, json$) ' JSON string → array, returns element count
LOADJSON arr$, "file.json" ' Load JSON file
SAVEJSON arr$, "file.json" ' Save JSON file
```
`ASARRAY` on an empty string is an error. A failed `HTTPGET`/`HTTPPOST` returns `""`, so check `HTTPERROR` before passing the response to `ASARRAY`.
`ASJSON`/`SAVEJSON` emit a JSON **array** at a level only when all its keys are canonical non-negative ints (`"0"`, `"1"`, ... — no sign, leading zeros or spaces) and the max index is <= 1,000,000 or the level is dense (max < 4*count+64); otherwise a JSON **object** with the original keys. A huge key (`arr$("2147483647")`) returns instantly as an object instead of freezing (before 1.7); `"-5"`/`"007"` keys are kept as properties, not dropped. `ASARRAY`/`LOADJSON` read both shapes back to the same keys (arrays → `"0".."n-1"`, objects → verbatim names; `null` holes skipped).
Keys keep their case in both directions (D12): `arr$("key")` and `arr$("KEY")` stay two keys — `ASJSON` gives `{"key":"lower","KEY":"upper"}`, at every nesting level. Before 1.7 the write path collapsed case-differing keys and lost a value.
### XML (light model)
`ASARRAY` also reads XML. It picks the format from the first character: `{` or `[` = JSON, `<` = XML (BOM and whitespace skipped). **Prefer JSON.** Use XML only when the task requires it — an RSS/Atom feed, or an API or file that only offers XML. JSON keys are shorter, numbers stay numbers, and it maps to arrays cleanly.
```basic
LET n$ = ASARRAY(feed$, xml$) ' XML string → array
LET xml$ = ASXML(arr$) ' Array → XML string
LOADXML arr$, "file.xml" ' Load XML file
SAVEXML arr$, "file.xml" ' Save XML file (indented, with <?xml ...?>)
```
- **Every element below the root is indexed, even a single one.** Never drop the `,0`: `feed$("rss,channel,0,item,0,title,0")`, not `feed$("rss,channel,item,title")`.
- Attributes: `...,guid,0,@isPermaLink`. Text of an element that also has attributes or children: `...,guid,0,#text`.
- Prefixes kept as written: `...,dc:creator,0`. CDATA is plain text. Comments and DTDs are ignored.
- All values are strings — use `VAL()` for numbers. Mixed text-and-element order is lost.
- `ASXML`: a single top-level key becomes the root element, otherwise `<root>`. Keys must be valid XML names (no spaces).
- XML is not HTML: a web page does not parse as XML.
```basic
' RSS reader
LET xml$ = HTTPGET("https://www.example.com/rss.xml")
IF HTTPERROR <> "" THEN
PRINT "Feed is down: "; HTTPERROR
END
END IF
DIM feed$
LET n$ = ASARRAY(feed$, xml$)
PRINT feed$("rss,channel,0,title,0")
LET i$ = 0
WHILE HASKEY(feed$("rss,channel,0,item," + i$ + ",title,0"))
PRINT "- "; feed$("rss,channel,0,item," + i$ + ",title,0")
i$ += 1
WEND
END
```
### Passing Arrays to Functions
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.
```basic
DEF FN ProcessPlayer$(data$)
DIM arr$
LET count$ = ASARRAY(arr$, data$)
RETURN arr$("name") + " score:" + arr$("score")
END DEF
[inits]
DIM player$
player$("name") = "Alice"
player$("score") = 9999
player$("address,city") = "New York"
[main]
LET json$ = ASJSON(player$)
PRINT FN ProcessPlayer$(json$)
END
```
---
## Date & Time
```basic
LET t$ = TIME() ' Default "HH:mm:ss" -> "15:21:22"
LET t2$ = TIME("dd.MM.yyyy") ' .NET DateTime format -> "04.09.2026"
LET t3$ = TIME("dddd") ' -> "Friday"
LET start$ = TICKS ' Milliseconds since program start
```
**Timing — SLEEP and TICKS do different jobs:**
- **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.
- **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).
- **TICKS:** use for measuring time — timers, cooldowns, animation speed, and movement that should stay the same speed on every monitor.
```basic
[inits]
LET running$ = TRUE
LET lastTick$ = TICKS
LET delta$
LET x$ = 0, speed$ = 2 ' several variables in one LET
[main]
WHILE running$
delta$ = TICKS - lastTick$
lastTick$ = TICKS
x$ = x$ + speed$ * delta$ / 16 ' same speed regardless of frame rate
GOSUB [sub:draw]
WEND
END
```
---
## Command-Line Arguments
```basic
' bazzbasic.exe myprog.bas arg1 arg2
PRINT ARGCOUNT ' 2
PRINT ARGS(0) ' "arg1"
PRINT ARGS(1) ' "arg2"
```
0-based; does not include the interpreter or script name.
Packaged `-exe` programs receive arguments identically (`prog.exe arg1 arg2`); inside a packaged exe, flags like `-v` are not special — they arrive as ordinary ARGS() strings.
---
## Libraries & INCLUDE
```basic
INCLUDE "helpers.bas" ' Insert source at this point
INCLUDE "MathLib.bb" ' Load compiled library
' Compile library (functions only — no loose code)
' bazzbasic.exe -lib MathLib.bas → MathLib.bb
' Function names auto-prefixed: MATHLIB_functionname$
PRINT FN MATHLIB_add$(5, 3)
```
- Library functions can read main-program constants (`#`).
- `.bb` files are **version-locked** to the build that produced them — recompile after upgrading.
- **No extension fallback:** `INCLUDE "helpers"` does NOT try `helpers.bas`.
- **Path resolution:** relative to the including file's directory first, then the program's base path.
- **Circular includes** halt with `Circular INCLUDE detected: <file>`.
- A .bb library is never embedded into an -exe package - ship it next to the exe (only .bas INCLUDEs are embedded).
---
## Program Structure
```basic
' ---- 1. FUNCTIONS (or INCLUDE) ----
DEF FN Clamp$(v$, lo$, hi$)
IF v$ < lo$ THEN RETURN lo$
IF v$ > hi$ THEN RETURN hi$
RETURN v$
END DEF
' ---- 2. INIT — declare ALL constants & variables here ----
[inits]
LET SCREEN_W# = 640
LET SCREEN_H# = 480
LET MAX_SPEED# = 5
LET PLAYER_COLOR# = RGB(0, 255, 0)
SCREEN 0, SCREEN_W#, SCREEN_H#, "My Game"
LET x$ = 320
LET y$ = 240
LET running$ = TRUE
' ---- 3. MAIN LOOP ----
[main]
WHILE running$
IF INKEY = KEY_ESC# THEN running$ = FALSE
GOSUB [sub:update]
GOSUB [sub:draw] ' SCREENLOCK OFF + VSync paces the loop to the monitor refresh rate
WEND
SOUNDSTOPALL
END
' ---- 4. SUBROUTINES (or INCLUDE) ----
[sub:update]
IF KEYDOWN(KEY_LEFT#) THEN x$ = x$ - MAX_SPEED#
IF KEYDOWN(KEY_RIGHT#) THEN x$ = x$ + MAX_SPEED#
RETURN
[sub:draw]
SCREENLOCK ON
LINE (0,0)-(SCREEN_W#, SCREEN_H#), 0, BF
CIRCLE (x$, y$), 10, PLAYER_COLOR#, 1
SCREENLOCK OFF
RETURN
```
**Naming conventions:** variables `camelCase$`, constants `UPPER_SNAKE_CASE#`, functions `PascalCase$`, labels `[gameLoop]` for jump targets and `[sub:name]` for subroutines.
---
## IDE
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.
| Menu | Items |
|------|-------|
| **File** | New, Open, Save, Save As, Save All, Close Tab, Close All, Restore Session on Startup¹, Print, Exit |
| **Edit** | Undo, Redo, Cut, Copy, Paste, Select All, Comment Selection, Uncomment Selection |
| **Search** | Find, Replace |
| **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 |
| **Run** | Run Program (F5), Compile as Exe, Compile as Library (.bb), Path to BazzBasic.exe³ |
| **Help** | About, Homepage, Online Manual, Beginner's Guide, Rosetta Code, Check for Updates |
¹ Saved to `%AppData%\BazzBasic\ide.json`
² Opens in the current file's folder
³ Used if set; otherwise the IDE's own folder, then `PATH`
- Compile commands auto-save the file first.
- Help-menu links open the URLs listed at the top of this guide.
- CLI equivalents: `bazzbasic.exe -guide` / `-help` prints the Beginner's Guide URL, `bazzbasic.exe -checkupdates` checks for a newer version.
- New files get this template:
```basic
' BazzBasic version {ver_num}
' https://ekbass.github.io/BazzBasic/
``` |