---
name: chipmunk-basic-mac
description: Write, port, review or debug programs for the Chipmunk Basic interpreter on macOS (current Cocoa builds, 1.368.x / 3.6.8 series). Use whenever code must run in Chipmunk Basic, or when converting GW-BASIC, QBasic, Applesoft or other classic BASIC to it.
---

# Chipmunk Basic (Mac) Skill

**Purpose**: Produce correct, readable code in Chipmunk Basic's particular dialect, and avoid the habits from other BASICs that silently break here.
**Version context**: Current Mac builds by Ronald H. Nicholson Jr. (latest release 1.368.2210, Nov 2022; runs on Intel and Apple Silicon). Builds 3.6.7 and later were rewritten for Cocoa, so many Carbon-era Mac features (macfunction calls, some GUI, sprite and sound commands) are missing or broken.
**Official references**: http://www.nicholson.com/rhn/basic/ — the Reference Manual (`basic.man.html`, written for v3.6.6, still the language reference) and the Mac Readme / Quick Reference (`readme.cbas.html`).

**Confidence markers used below**
- No marker: stated in the official manual or readme.
- **(verify)**: plausible or community-reported but not in the official docs; test on the target build before relying on it.

---

## 1. Overview

Chipmunk Basic is a freeware, old-fashioned BASIC interpreter with structured extensions. It follows ANSI Minimal BASIC in many places and is "mostly compatible with BASIC books from about 1978–1990", but it is **not** GW-BASIC, QBasic or QuickBASIC. Several familiar keywords behave differently (`rnd`, `instr`, `not`, `input`, `dim`, `data`), and several QBasic keywords are reserved but **not implemented** (`do`, `loop`, `function`, `swap`, `redim`, `resume`, ...).

Keywords and variable names are case-insensitive. Numbers are IEEE doubles; strings are the other main type.

## 2. Running Programs

- **Terminal**: `basic myprog.bas` runs a file with the command-line binary. `basic ":print 2+2"` executes one statement (an argument starting with `:`).
- **App**: File > Open, or `load "myprog.bas"` then `run` at the console. The Open menu only accepts files ending in `.bas`.
- The default file directory for relative paths is the user's Documents folder (3.6.7+). Use full paths when in doubt.
- On load, lines starting with `#` are treated as comments, so a first line of `#!/usr/local/bin/basic` (or wherever `basic` is installed) lets a `chmod +x` file run directly from the shell.
- The pragma line `#cbas#run_only` makes the interpreter quit (instead of dropping to the console) on `stop`, `end` or Ctrl-C — useful for command-line tools.
- `exit(code)` exits the interpreter with a Unix status; `argv$` returns the command-line arguments (Terminal build).
- Cmd-period stops a running program in the app; Ctrl-C in Terminal.

## 3. Program Text Rules

### 3.1 Line numbers are optional in files

- **Interactive console**: every line needs a line number.
- **Loaded from a file**: line numbers may be omitted; the interpreter assigns sequential numbers on load. Do not mix numbered and unnumbered lines in one file.
- Valid line numbers are 1 to 2147483647; lines above 999999999 will not `list`.
- `save "prog.bas", "NLN"` saves without line numbers (only if the program uses labels, not numeric `goto` targets).
- **Each program line must be 254 characters or fewer.**

### 3.2 Labels

A label is a name followed by a colon at the start of a line. Use it as a `goto` / `gosub` target, and with `restore` (3.6.4b5+).

```basic
countdown:
  print x
  x = x - 1
  if x > 0 then goto countdown
```

- The readme's own example writes `goto foo:`; the trailing colon there is just a statement separator and is optional.
- **Never use a reserved word as a label** (`loop:`, `do:`, `exit:`, `end:`, `next:` etc. will break — see §13).
- `on error goto`, `on ... goto/gosub` and `open ... else goto` are documented with line numbers; labels are expected to work there too **(verify)**.

### 3.3 Statements and comments

- Multiple statements per line are separated by `:`.
- Comments: `rem`, `'` or `` ` ``. A `rem` line can be a `goto` target.
- After a statement that can end in a string (e.g. `print "x"`), a bare `'` comment sometimes fails; write `: '` instead, e.g. `print "hi" : ' greet`.
- Since 3.6.8b1.16 a remark directly after `then` is an **error**. Put the comment on the next line.
- There are no escape sequences in string literals. Use `chr$(34)` for a double quote, `chr$(9)` tab, `chr$(10)` LF, `chr$(13)` CR.
- Hex literals: `0x2AE` or `&h2AE`. Do **not** use `&` for string concatenation; use `+`.
- `#ifndef _chipmunkbasic_` ... can be used to make the interpreter skip code meant for other BASICs (3.6.4b5+) **(verify exact closing directive on your build)**.

## 4. Variables and Data Types

- Names: start with a letter; then letters, digits or underscores; up to 31 significant characters; case-insensitive.
- Suffix `$` = string, no suffix = double, `%` = 16-bit integer (−32768..32767).
- **Avoid `%` variables.** Arithmetic on them is still floating-point, `for` loops with `%` indices need the variable named in `next`, integer arrays are 1-D only and only work in assignment statements. Use plain numeric variables.
- **Names starting with `fn` are reserved** (for the obsolete `def fn`). Do not name variables `fname$`, `fnum`, `fnd` etc.
- Strings hold up to **254 characters**. Concatenation (`+`), `mid$`, `len` and `instr` handle up to 32766 characters, but most other string functions **silently truncate to 254**, and long strings are slow.
- Undeclared numeric variables start at 0 and strings at "" **(verify for strings)**; there is no `option explicit`.
- `let` is optional.

## 5. Arrays

- **Every array must be `dim`ed before use.** There is no automatic `dim a(10)` as in GW-BASIC.
- `dim a(10)` allocates **11** elements, subscripts **0 through 10**. This is true regardless of `option base`, which only affects `mat` statements.
- Up to 4 dimensions: `dim grid(9, 9), names$(50)`.
- `ubound(a)` = highest subscript of dimension 1; `ubound(a, 2)` for dimension 2. `isarray(a)` returns the number of dimensions or 0.
- `erase a` frees an array (needed before re-`dim`). `redim` is reserved but **not supported**.
- `mat` statements (fill, copy, add, multiply, `trn`, `inv`, `mat print`, `mat read`, `det()`, `fn dot()`) use origin **1** by default; change with `option base 0|1` or `mat origin 0|1`. Mixing `mat` code with 0-based loops is a common off-by-one source.

## 6. Operators, Truth Values and Precedence

| Operator | Meaning |
|---|---|
| `^` | exponent |
| `* / mod` | multiply, divide, remainder |
| `+ -` | add, subtract (`+` also joins strings) |
| `= <> < > <= >=` | comparison (numbers or strings) |
| `not` | **logical** not (any non-zero → 0, zero → 1) |
| `and or xor` | **bitwise** |

- **Comparisons return 1 for true and 0 for false** (not −1 as in Microsoft BASICs). Don't test `= -1`; reserved words `true` / `false` exist.
- Because `and` / `or` are bitwise, they are only safe on 0/1 values. `if a and b then` with `a = 2, b = 1` is **false** (2 and 1 = 0). Write `if a <> 0 and b <> 0 then`.
- `not` is logical, so `not 5` is 0. For a bitwise NOT of a 16-bit value use `x xor 0xFFFF`.
- There is **no** integer-division operator `\`. Use `int(a / b)` (rounds toward −∞) or `int(a / b, 0)` (toward zero).
- No short-circuit evaluation: both sides of `and` / `or` are always evaluated.

**Precedence (high to low)**:
`( )` → functions → `^` → unary `-` → `* / mod` → `+ -` → comparisons → `not` → `and` → `or xor`

Consequences: `-2^2` is −4 (ANSI). `not a = b` means `not (a = b)`. Use parentheses whenever mixing logic with arithmetic. (`#cbas#non_ansi_not` / `#cbas#non_ansi_neg` restore old precedences; don't rely on them.)

## 7. Control Flow

### 7.1 IF

```basic
if x > 0 then print "positive"
if x > 0 then print "pos" else print "not pos"     ' colon before else optional (3.6.4+)
if done then 500                                   ' then LINENUM = goto

if x > 100 then
  print "big"
else
  if x > 10 then
    print "medium"
  else
    print "small"
  endif
endif
```

- A block IF is an `if` line with **nothing after `then`**. `then` may be omitted if the condition is parenthesized: `if (x > 0)`.
- Close blocks with **`endif`** (one word). Block IFs nest.
- **There is no else-if chaining. Neither `elseif` (one word) nor `else if` (two words) works**, even though older docs mention `elseif` and it is still a reserved word. For a multi-way test, nest a new block IF inside the `else` branch, giving each its own `endif` (as above), or use `select case` when testing one value.
- Single-line IF: everything after `then` on that line, including later `:`-separated statements, belongs to the IF.
- Inline conditional expression: `y = if(x > 0, 1, -1)` (3.6.4b2+).

### 7.2 Loops

```basic
for i = 1 to 10 step 2
  if i = 7 then exit for
  print i
next i

while n > 0
  n = n - 1
  if n = 3 then exit while
wend
```

- Always name the variable in `next` (`next i`). `next j, i` closes two loops.
- A `for` body is skipped entirely if the start already passes the limit.
- `while` with no expression loops forever (`while` ... `wend` + `exit while` is the general-purpose loop).
- **No `do` / `loop` / `until` / `repeat`.** Convert `DO ... LOOP UNTIL c` to `while 1` ... `if c then exit while` ... `wend`.
- `wend expr` exits if `expr` is true; avoid it for readability.

### 7.3 SELECT CASE

```basic
select case cmd$
  case "q", "quit"
    running = 0
  case "h"
    show_help()
  case else
    print "Unknown command"
end select
```

- `case` takes a comma-separated list of values. `case else` is the default.
- Ranges (`case 1 to 5`) and `case is > 5` are **not documented** (`is` is a reserved, unimplemented word). Use nested block IFs for ranges (no `elseif`; see §7.1).

### 7.4 GOTO / GOSUB / ON

- `gosub label` ... `return` works; recursion depth is limited only by memory.
- `on k goto a, b, c` / `on k gosub ...`: if `k` is out of range, execution falls through (no error). Prefer `select case`.

## 8. Named Subroutines (SUB)

Chipmunk Basic has no `function` keyword; a SUB can both be called as a statement and used as a function in an expression.

```basic
total = add(3, 4)          ' used as a function
call report(total)         ' or: report(total)
end

sub add(a, b)
  add = a + b              ' return value: assign to the sub's name
end sub

sub report(v)
  print "Total = "; v
end sub
```

**Rules**
- Parameters become local variables. Numbers and strings are passed **by value**; arrays are passed **by reference** and must already be `dim`ed.
- If the caller passes fewer arguments than declared, the missing parameters are locals set to 0 (or "") — a cheap way to get scratch locals.
- Declare other locals with `local a, b$` (3.6.4b7+) or `def local a, b$` (3.6.4b6+). **Any variable not declared as a parameter or local is global.** Always declare loop counters local, or a recursive/nested call will corrupt the caller's loop.
- `static v` keeps its value between calls (not safe in recursion). The SUB name plus any static variable names must total fewer than 29 characters.
- **A SUB that returns a string must have a name ending in `$`**: `sub pad$(s$, n)` ... `pad$ = r$`.
- SUBs may not be nested. Variables used as `class` / `type` instances globally override locals of the same name.
- **Exactly one exit per SUB**: the manual says there should be only one `return` or `end sub` in each SUB definition, so there is no early exit and no `exit sub`. Structure the body with block IFs, a result variable and `exit for` / `exit while`.
- `return (expr)` with mandatory parentheses is reported to return a value from a SUB that ends with `return` instead of `end sub` **(verify — not in the official manual)**. Prefer `name = value` ... `end sub`. Never write bare `return value`.
- Recursion works because parameters and `local` variables are per call. `push` / `pop` can save globals or whole arrays across recursive calls.
- Named SUBs are slower than `gosub`; this only matters in tight loops.
- An error inside a SUB cannot be resumed with `cont` or `on error goto`.
- Place SUB definitions after the main program's `end` so execution never falls into them. Calling a SUB that is defined later in the file is fine.
- Old single-line functions `def fnsq(x) = x * x` still work but are obsolete; use SUBs.

## 9. Input and Output

### 9.1 PRINT

- `,` between items inserts a tab; `;` inserts nothing; a trailing `;` suppresses the newline. `?` is short for `print`.
- `tab(n);` inside a print list moves to column `n`.
- `print using "###.##"; x` — the format accepts only `+ * $ # .`, `E+` and trailing spaces. **Commas, underscores and `&` are not recognized.**
- `format$(x, "###.##")` returns the same formatting as a string; `str$(x, width)` pads to a width; `hex$(x, width)` / `bin$(x, width)` zero-pad.
- Do not assume Microsoft's leading-space-for-sign rule in numeric output; format explicitly when layout matters **(verify)**.

### 9.2 INPUT — every string input is a whole line

```basic
input "Your name? ", who$       ' manual form: prompt then comma
input "Two numbers: "; a, b     ' semicolon form also documented
```

- Input into a **string** variable always reads the entire line (like `LINE INPUT`), commas included. There is no separate `line input` statement.
- Input into **numeric** variables accepts comma-separated values; the line may hold fewer values than there are variables, never more.
- For mixed or free-form input, read one string and split it with `field$` (§9.3).
- `val()` **evaluates expressions**: `val("1 + sqr(4)")` is 3, and a word like `"abc"` may be read as a variable name. Validate user text before `val()` if that matters.
- `inkey$` returns one key or "" (non-blocking); `get k$` waits for one key; `input$(n)` reads `n` characters.

### 9.3 Splitting text with `field$`

```basic
field$(s$, n)            ' n-th field, separated by spaces
field$(s$, n, sep$)      ' first character of sep$ is the separator
field$(s$, -1, sep$)     ' a string whose LENGTH equals the number of separators
```

```basic
item$   = field$("aa bb cc", 2)           ' "bb"
color$  = field$("red,green,blue", 2, ",")  ' "green"
col$    = field$(row$, 3, chr$(9))         ' 3rd column of a TSV line

nfields = len(field$(row$, -1, chr$(9))) + 1   ' count fields: len(), not val()
```

- `field$(s$, n, sep$) = new$` replaces the n-th field in place.
- How runs of repeated spaces are treated with the default separator is not documented **(verify)**. When parsing user input, prefer an explicit separator such as `","`, or collapse doubled spaces first.

### 9.4 DATA / READ / RESTORE

```basic
data "apple", 3, "pear", 5
read fruit$, qty
restore fruits          ' jump to the DATA at or after label "fruits"
```

- **String items must be in quotes.** Unquoted words in `data` will not read correctly.
- Reading past the last item is an error; reading a string into a numeric variable gives "Type mismatch".

## 10. Files, OS and Errors

### 10.1 Sequential files

```basic
open "scores.txt" for output as #1
print #1, "alice"; chr$(9); 92
close #1

open "scores.txt" for input as #1
while 1
  input #1, rec$
  if eof(1) then exit while       ' check AFTER reading, BEFORE using
  print field$(rec$, 1, chr$(9)); " scored "; field$(rec$, 2, chr$(9))
wend
close #1
```

- Modes: `input`, `output`, `append`; file numbers 0–8 (use 1–8). `"stdin"` / `"stdout"` as the name use the console.
- **`eof()` only becomes true after a read attempt fails.** Reading the last line does not set it, and reading past the end is not an error. Always read, test `eof`, then use the data — as above.
- `open f$ for input as #1 else goto nofile` traps a failed open (sets `erl`).
- `open f$ for data input as #n` / `for data output` opens without CR/LF translation (needed to read `chr$(13)`).
- Byte and record I/O: `fgetbyte(n)`, `fputbyte b, #n`, `fseek #n, pos`, `open f$ for random as #n len = size` with `get #n, rec, var` / `put #n, rec, var` on `type` records.
- `fn kill(f$)` deletes a file (returns 0 on success). `files` / `dir` list a directory.
- Simple key–value database: `dim db$ as dbm$("mydb")`, then `db$(key$) = value$`, `close db$`.

### 10.2 Shell, pipes, time

- `sys(cmd$)` runs a shell command and returns its exit status; `system$(cmd$)` returns the first line of its output; `getenv$(name$)`.
- `open "pipe:ls -l" for input as #1` reads a command's output; pipes for output and `"socket:host", port` also work.
- `date$`, `time$`, `timer` (seconds), `fn sleep(seconds)` (fractions allowed).
- `exec("print x")` runs a string as a statement; `fn eval(...)` evaluates one **(verify argument form)**.

### 10.3 Error handling

```basic
on error goto handler
open "missing.txt" for input as #1
print "opened"
end

handler:
  print "Error: "; errorstatus$; " at line "; erl
  end
```

- `errorstatus$` holds the error message; `erl` the line number. There is no documented `err` code.
- **No `resume`.** Continue with `goto` to a label, or `cont` from the console.
- Errors inside a named SUB cannot be resumed.

## 11. Built-in Function Reference (and what is missing)

**Numeric**: `abs sgn sqr exp log log10 sin cos tan atn atn(y,x) asin acos sinh cosh tanh pi floor int(x) int(x,0) rnd randomize`, `ubound isarray`, `fn math$()` (250-digit arithmetic on number strings).

- `int(x)` rounds toward −∞ (like `floor`); `int(x, 0)` truncates toward 0. `|x|` must be under 2^31.
- Trig uses radians unless `option degrees` is set.
- **`rnd(n)` returns an integer from 0 to n−1.** Only `rnd(1)` returns a fraction in [0, 1). A die roll is `rnd(6) + 1`; a float in [a, b) is `a + rnd(1) * (b - a)`. A negative argument seeds the generator. `randomize timer` seeds from the clock **(verify)**.

**String**: `len left$ right$ mid$ instr chr$ asc str$ val hex$ bin$ lcase$ ucase$ field$ format$ inkey$ input$`, plus `mid$(s$, i, n) = x$` assignment.

- **`instr(a$, b$, start)` — the start position is the optional THIRD argument**, unlike Microsoft's `INSTR(start, a$, b$)`. Returns 0 if not found; positions are 1-based.
- `mid$(a$, i)` without a length returns the rest of the string.
- String comparisons with `= <> < > <= >=` return 1 or 0.

**Not available** — write helpers instead: `space$`, `string$`, `trim$` / `ltrim$` / `rtrim$`, `replace$`, `instrrev`, `fix`, `round`, `ceil`, `min`, `max`, `\`, `swap`, `const`, `sleep` (use `fn sleep`). `min`, `max` and `swap` are reserved, so don't use those names for your own SUBs either.

### Helper SUBs

```basic
sub repeat$(s$, n)
  local r$, i
  r$ = ""
  for i = 1 to n
    r$ = r$ + s$
  next i
  repeat$ = r$
end sub

sub rtrim$(s$)
  local k
  k = len(s$)
  while k > 0
    if mid$(s$, k, 1) <> " " then exit while
    k = k - 1
  wend
  rtrim$ = left$(s$, k)
end sub

sub ltrim$(s$)
  local k
  k = 1
  while k <= len(s$)
    if mid$(s$, k, 1) <> " " then exit while
    k = k + 1
  wend
  ltrim$ = mid$(s$, k)
end sub

sub roundn(x, places)            ' round half away from zero
  local m
  m = 10 ^ places
  roundn = sgn(x) * int(abs(x) * m + 0.5) / m
end sub

sub smaller(a, b)
  smaller = a
  if b < a then smaller = b
end sub
```

Ceiling of `x` is `-floor(-x)`; truncation is `int(x, 0)`.

## 12. Mac Console and Graphics (Cocoa builds)

Prefer plain console code unless graphics or sound are explicitly requested. The following are documented for Mac; because the Cocoa rewrite dropped many Carbon features, **verify each on the target build**:

- Console: `cls` (or `home`), `gotoxy col, row` (0-based, column first), `pos(0)` / `pos(-1)` for cursor column / row.
- Graphics window: `graphics 0` (open / refresh), `graphics -1` (hide), `graphics cls`, `graphics window x, y, w, h`.
- Drawing: `graphics moveto x, y`, `graphics lineto x, y`, `graphics pset x, y`, `graphics rect x1, y1, x2, y2`, `graphics fillrect x1, y1, x2, y2`, `graphics circle d`, `graphics color r, g, b` (each **0–100**, not 0–255), `graphics drawtext s$`, `graphics pict x, y, file$`.
- `fn scrn(x, y, c)` reads a pixel; `fn saveaspng(f$, x, y, w, h)`; `fn plot1(...)` quick function plots.
- Sound: `say "text"`, `sound freq, seconds, volume`, `morse "text"`, `fn playsound(file$, secs)`.
- Mouse: `mouse(0)` button, `mouse(1)` / `mouse(2)` x / y (call after a graphics command).

```basic
graphics 0
graphics color 100, 0, 0
graphics moveto 10, 10
graphics lineto 200, 120
graphics color 0, 0, 0
```

Treat `macfunction(...)`, `inputbox`, `menu`, `graphics button`, sprites, serial ports, MIDI and Bluetooth commands as Carbon-era or experimental: don't generate them unless the user asks and can test.

## 13. Reserved Words — never use as variable, label or SUB names

```
+ - * / ^ mod and or xor not eqv imp
abs acos asin atn cos cosh exp floor int log log10 pi rnd sgn sin sinh sqr tan tanh
asc chr$ field$ hex$ bin$ instr lcase$ ucase$ left$ len mid$ right$ str$ val
if then else elseif endif for to step next while wend select case
goto gosub return on error sub call usr def fn local static end stop exit quit bye cont
rem let dim erase data read restore option degrees radians base mat origin
input print using open output append random as close load save merge run new clear
list renum edit del lof loc get put eof inkey$ input$ files dir fgetbyte fputbyte fseek
date$ time$ timer sound morse say doevents home cls gotoxy htab vtab pos window
graphics sprite pset moveto lineto scrn mouse menu inputbox varptr peek poke fre push pop
isarray ubound type class extends new string integer longint single double true false
this exec bload bsave dbm$ redim do loop until break function method private public
dialog memstat draw play min max each resume key is set width swap msgbox filename$
```

Also reserved: any name beginning with `fn`. When in doubt, add a project prefix or suffix (`cnt`, `itemcount`, `cmd_loop`).

## 14. Porting Checklist (GW-BASIC / QBasic / Applesoft → Chipmunk)

| In the source program | Do this in Chipmunk Basic |
|---|---|
| Line numbers everywhere | Remove them; turn `GOTO`/`GOSUB` targets into labels |
| Arrays used without `DIM` | Add `dim` for every array (no implicit size 10) |
| `OPTION BASE 1` for ordinary arrays | Has no effect outside `mat`; adjust loops (`dim a(n)` gives 0..n) |
| `RND` returning a fraction, `RND(1)*N` | Same for `rnd(1)`; but `rnd(n)` with n>1 returns an integer 0..n−1 |
| `RANDOMIZE` with no argument | Give a seed: `randomize timer` |
| `INSTR(start, a$, b$)` | `instr(a$, b$, start)` |
| Truth tests against −1, `NOT` as bitwise | Truth is 1/0; `not` is logical; use `xor 0xFFFF` for bitwise NOT |
| `A AND B` on non-0/1 values as a logical test | Compare explicitly: `(a <> 0) and (b <> 0)` |
| `\` integer division | `int(a / b)` or `int(a / b, 0)` |
| `LINE INPUT a$` | `input a$` |
| `INPUT A, B$, C` mixed types | `input s$` then `field$` + `val` |
| Unquoted strings in `DATA` | Quote every string item |
| `FUNCTION f(x) ... END FUNCTION` | `sub f(x)` ... `f = value` ... `end sub` (string results: `sub f$(...)`) |
| `EXIT SUB` / `EXIT FUNCTION`, multiple `RETURN` in a SUB | Restructure to a single exit with a result variable |
| `SHARED`, `DIM SHARED`, `COMMON` | Not needed — undeclared names inside SUBs are global; declare the rest `local` |
| `DO ... LOOP [UNTIL/WHILE]` | `while` ... `wend` with `exit while` |
| `END IF` | `endif` |
| `CASE 1 TO 5`, `CASE IS > 3` | Nested block IFs |
| `ELSEIF` / `ELSE IF` chains | Nest a block IF inside `else`, each with its own `endif` |
| `SWAP a, b` | `t = a : a = b : b = t` |
| `SPACE$`, `STRING$`, `TRIM$`, `FIX`, `CINT` | Helper SUBs from §11, `int(x, 0)`, `int(x + 0.5)` |
| `DEFINT`, `%` everywhere | Drop it; use doubles |
| `LOCATE row, col` | `gotoxy col - 1, row - 1` (0-based, column first) |
| `SLEEP n` | `fn sleep(n)` |
| `PRINT USING` with commas or `&` | Simplify the format or build the string by hand |
| `ON ERROR GOTO` + `RESUME` | `goto` back to a label; no resume |
| `CONST X = 5` | Plain variable assignment at the top |
| String concatenation with `&` (VB-style) | `+` |
| Statement lines over 254 chars | Split across lines |
| Variables named `fname$`, `loop`, `max`, `width`, `key`... | Rename (§13) |

## 15. Readable Code Conventions

1. Start each file with a comment block: program name, purpose, inputs and outputs.
2. Lowercase keywords; two-space indentation inside `if`, `for`, `while`, `select` and `sub` bodies.
3. Order: header → setup (`dim`, constants, `data` labels) → main program → `end` → SUBs → `data` blocks.
4. One statement per line, except short idioms like `t = a : a = b : b = t`.
5. Prefer `sub` over `gosub`, and `while`/`for`/`select` over `goto`. Use labels only for `restore`, error handlers and rare jumps.
6. Use descriptive names up to 31 characters; separate words with underscores (`total_score`, `read_scores`).
7. Declare every SUB-internal variable with `local`; give each SUB one exit and assign its return value just before `end sub`.
8. Parenthesize compound conditions: `if (x > 0) and (y > 0) then`.
9. Name string-returning SUBs with `$`.
10. Keep each line under 254 characters and keep string values under 254 characters.

## 16. Complete Examples

### Factorial with a value-returning SUB

```basic
' factorial.bas -- compute n! using a named subroutine
input "Enter n: ", n
print "Factorial = "; factorial(n)
end

sub factorial(n)
  local i, prod
  prod = 1
  for i = 2 to n
    prod = prod * i
  next i
  factorial = prod
end sub
```

### Parsing one line of input

```basic
' greet.bas -- read name, age and score on one line
input "Name age score (space separated): ", s$
who$  = field$(s$, 1)
age   = val(field$(s$, 2))
score = val(field$(s$, 3))
print "Hello "; who$; ", age "; age; ", score "; score
end
```

### Menu loop with SELECT CASE and a string SUB

```basic
' menu.bas -- simple command loop
running = 1
while running
  input "Command (r=roll, b=banner, q=quit): ", cmd$
  select case lcase$(cmd$)
    case "r"
      print "You rolled "; rnd(6) + 1
    case "b"
      print banner$("Chipmunk", "*")
    case "q"
      running = 0
    case else
      print "Unknown command: "; cmd$
  end select
wend
print "Bye."
end

sub banner$(text$, ch$)
  local edge$, i
  edge$ = ""
  for i = 1 to len(text$) + 4
    edge$ = edge$ + ch$
  next i
  banner$ = edge$ + chr$(10) + ch$ + " " + text$ + " " + ch$ + chr$(10) + edge$
end sub
```

### Reading DATA into an array

```basic
' fruits.bas -- load quoted DATA into arrays, then report
dim fruit$(4), qty(4)
restore fruit_data
for i = 0 to 4
  read fruit$(i), qty(i)
next i

for i = 0 to ubound(qty)
  print fruit$(i); tab(12); qty(i)
next i
end

fruit_data:
data "apple", 3, "pear", 5, "plum", 0, "fig", 12, "kiwi", 7
```

## 17. Verification Before Delivering Code

- Run it: `basic prog.bas` in Terminal (or load in the app) and exercise every branch.
- Grep the code for: `do`, `loop`, `function`, `end if`, `elseif`, `else if`, `exit sub`, `\`, `swap`, `space$`, `string$`, `trim$`, `&` used for joining strings, `instr(` with a numeric first argument, unquoted `data` strings, `rnd(` with an argument other than 1 where a fraction was intended, arrays used without `dim`, variables beginning with `fn`, string SUBs without `$`, and more than one `return`/`end sub` in a SUB.
- Check every SUB declares its loop counters `local`.
- Check file-reading loops test `eof` after each read.
- Anything marked **(verify)** in this skill must be tested on the user's build before it is relied on.
