BBC BASIC reference
Every command, function and operator in BBC BASIC, shared by the BBC Micro and the BBC Master.
In this reference: Hardware · Escape codes · File formats · Argument notation
Notes and caveats
- A keyword can be typed as a dotted prefix —
P.forPRINT,GOS.forGOSUB— which the ROM expands to the first keyword in its own lookup order that the letters begin. The shortest form of each is shown beside it in the table below, and the search box finds a keyword by it. - Case matters here, and on both counts. A keyword is matched byte for byte against an upper-case table, so
printis notPRINT— it is a variable name, and the line will not do what it says; the editor colours it as a name and reports it. AndaandAare two different variables, unlike almost every other machine here, so a program that uses both keeps two. Lower case itself is stored as written and lists back as written. - BBC BASIC reaches memory through the indirection operators
?(byte),!(word) and$(string) rather thanPEEK/POKE; all three are in the table below. The@%print-format variable is a variable rather than an operator, so it is not. - The power operator is
^, and it folds left to right:2^3^2is64. AND,OR,NOTandEORcombine their operands bit by bit —5 AND 3is1— and a true comparison is-1.DIVandMODare the integer division and remainder; the Atom that preceded this machine has neither, and answers1rather than-1to a true comparison.
Command Function Operator
| Syntax & description | |
|---|---|
- | <number> - <number> | -<number>Subtraction / negation. |
! | !<addr> | !<addr> = <number>Word indirection: reads or writes the four-byte word at an address, low byte first. |
? | ?<addr> | ?<addr> = <byte>Byte indirection: reads or writes the byte at an address - BBC BASIC has no PEEK or POKE. |
* | <number> * <number>Multiplication. |
/ | <number> / <number>Division. |
^ | <number> ^ <number>Raises to a power. Folds left to right, so 2^3^2 is 64. |
+ | <number> + <number> | <string> + <string>Addition / string concatenation. |
< | <number> < <number> | <string> < <string>Less than. |
<= | <number> <= <number> | <string> <= <string>Less than or equal. |
<> | <number> <> <number> | <string> <> <string>Not equal. |
= | <var> = <expr> | <expr> = <expr>Assignment / equality. A true comparison is -1. |
> | <number> > <number> | <string> > <string>Greater than. |
>= | <number> >= <number> | <string> >= <string>Greater than or equal. |
$ | $<addr> | $<addr> = <string>String indirection: the carriage-return-terminated string stored at an address. |
ABSAB. | ABS(<number>)Returns the absolute (unsigned) value of a number. |
ACSAC. | ACS(<number>)Returns the arc cosine of a number (the argument must be between -1 and 1), giving an angle in radians. |
ADVALAD. | ADVAL(<number>)Reads an analogue-to-digital converter channel or, with a negative argument, the free space in a buffer (keyboard, serial, sound). Used to read joysticks and check buffer status. |
ANDA. | <number> AND <number>Bitwise/logical AND of two integers; operands are coerced to 32-bit integers before the operation. Doubles as a logical AND in conditions because TRUE is -1 (all bits set) and FALSE is 0. |
ASCAS. | ASC(<string>)Returns the character code of the first character of a string, or -1 if the string is empty. |
ASN | ASN(<number>)Returns the arc sine of a number (the argument must be between -1 and 1), giving an angle in radians. |
ATNAT. | ATN(<number>)Returns the arctangent of a number, giving an angle in radians. |
AUTOAU. | AUTO [<line>[, <number>]]An immediate-mode command that generates line numbers automatically as you type, starting at the given line and stepping by the given amount (defaults 10, 10). Press Escape to stop. |
BGETB. | BGET#<file>Reads and returns the next byte (0–255) from an open file, advancing the file pointer. |
BPUTBP. | BPUT#<file>, <byte>Writes a single byte (0–255) to an open file at the current pointer, advancing it. |
CALLCA. | CALL <addr>[, <var>]…Calls a machine-code routine at the given address, optionally passing parameters whose addresses are listed in a parameter block for the routine. |
CHAINCH. | CHAIN <filename>Loads another BASIC program from the filing system and runs it immediately, clearing variables first. |
CHR$CHR. | CHR$(<number>)Returns the single-character string for a character code. Codes 128–159 are teletext control codes in MODE 7 (e.g. CHR$(129) for red text). |
CLEARCL. | CLEARDiscards all variables, arrays and procedure/function definitions, and forgets any pending GOSUB, FOR and REPEAT contexts. |
CLG | CLGClears the graphics area to the current graphics background colour set by GCOL. |
CLOSECLO. | CLOSE#<file>Closes an open file, flushing any buffered output; CLOSE#0 closes all open files at once. |
CLS | CLSClears the text area to the current text background colour and moves the cursor to the top-left. |
COLOURC. | COLOUR <colour>Sets the logical colour used for subsequently PRINTed text; adding 128 to the argument sets the text background instead. Use GCOL for graphics colours. The Master also supports COLOUR to redefine the palette. |
COS | COS(<number>)Returns the cosine of an angle given in radians. |
COUNTCOU. | COUNTReturns the number of characters printed to the screen since the last newline, useful for aligning columns of output. |
DATAD. | DATA <constant>[, <constant>]…Holds a list of constants (numbers or strings) read sequentially by READ; leading spaces are skipped and strings need quotes only if they contain commas. |
DEF | DEF PROC<name>[(<param>[, <param>]…)] | DEF FN<name>[(<param>[, <param>]…)]Marks the start of a user-defined procedure (DEF PROC) or function (DEF FN); BASIC skips over DEF lines during normal flow, so place them after END. |
DEGDE. | DEG(<number>)Converts an angle from radians to degrees. |
DELETEDEL. | DELETE <line>, <line>An immediate-mode command that deletes all program lines in the given range, inclusive. |
DIM | DIM <var>(<number>[, <number>]…) | DIM <var> <number>Dimensions an array with the given maximum subscripts (indices start at 0, so DIM A(10) gives 11 elements). The form DIM P% n instead reserves n+1 bytes of memory and returns the base address. |
DIVDI. | <number> DIV <number>Integer division, truncating any fractional part towards zero (e.g. 7 DIV 2 is 3). Operands are first converted to integers. |
DRAWDR. | DRAW <x>, <y>Draws a line in the current graphics colour from the graphics cursor to the given coordinates, then leaves the cursor there. Coordinates run 0–1279 by 0–1023 regardless of mode. |
EDITED.BASIC IV only | EDIT [<line>]An immediate-mode command that opens a line — or the whole program, given no line number — in the full-screen editor, where the program text can be changed in place and Escape returns to BASIC. Added by BASIC IV; it occupies the single token BASIC II leaves unused between SAVE and PTR. |
ELSEEL. | IF <number> THEN <statement> ELSE <statement>Introduces the alternative branch of a single-line IF…THEN, run when the condition is false. BBC BASIC supports ELSE, unlike some 8-bit dialects. |
END | ENDEnds program execution cleanly and returns to the command prompt; it may appear anywhere, not just at the physical end. |
ENDPROCE. | ENDPROCMarks the end of a DEF PROC definition and returns control to the statement after the PROC call. |
ENVELOPEENV. | ENVELOPE <envelope>, <number>[, <number>]…Defines one of the pitch/amplitude envelopes (numbered 1–4) that SOUND can use to shape a note over time; it takes 14 parameters controlling the attack, decay, sustain and release. |
EOFEO. | EOF#<file>Returns TRUE (-1) when the file pointer has reached the end of an open file, and FALSE (0) otherwise. |
EOR | <number> EOR <number>Bitwise exclusive-OR of two integers, setting each result bit where exactly one operand bit is set. Often used to toggle or flip bits. |
ERLER. | ERLReturns the line number at which the most recent error occurred; most useful inside an ON ERROR handler. |
ERR | ERRReturns the error number of the most recent error, letting an ON ERROR handler decide how to respond. |
ERRORERRO. | ON ERROR <statement> | ON ERROR OFFUsed after ON to install an error handler that runs when a runtime error is trapped; ON ERROR OFF restores the default handler. Inside a handler ERR and ERL give the error number and line. |
EVALEV. | EVAL(<string>)Evaluates a string as if it were a BASIC expression and returns the result, allowing formulae to be built or read in at run time. |
EXPEX. | EXP(<number>)Returns e (about 2.718) raised to the given power - the inverse of LN. |
EXT | EXT#<file>Returns the total length in bytes of an open file, useful for detecting how much data is available. |
FALSEFA. | FALSEThe constant 0, the value BASIC returns for a false condition. |
FN | FN<name>[(<arg>[, <arg>]…)]Calls a user-defined function created with DEF FN; the function returns a value via an = expression and may take parameters. |
FORF. | FOR <numvar> = <number> TO <number> [STEP <number>]Begins a counted loop, repeating the statements up to the matching NEXT while the counter runs from the start value to the limit. The body always executes at least once. |
GCOLGC. | GCOL <action>, <colour>Sets the graphics colour and plot action used by MOVE/DRAW/PLOT: the first argument is the plot mode (0 plot, 1 OR, 2 AND, 3 EOR, 4 invert) and the second the logical colour (add 128 for the background). Use COLOUR for text. |
GET | GETWaits for a key to be pressed and returns its character code; it blocks the program until a key is available. |
GET$GE. | GET$Waits for a key press and returns it as a one-character string (the string equivalent of GET). |
GOSUBGOS. | GOSUB <line>Calls a subroutine at the given line number, saving a return address so RETURN can resume after the call. Procedures (PROC) are preferred in structured BBC BASIC. |
GOTOG. | GOTO <line>Jumps unconditionally to the given line number. |
HIMEMH. | HIMEM | HIMEM = <number>A pseudo-variable holding the top of memory available to BASIC; lowering it reserves space above (for example for machine code), and changing screen MODE moves it. |
IF | IF <number> THEN <statement> [ELSE <statement>]Evaluates a condition (zero is false, non-zero true) and runs the THEN part if true, otherwise the optional ELSE part. The whole statement lives on one logical line. |
INKEY | INKEY(<number>)Waits up to the given number of centiseconds for a key and returns its code, or -1 if none was pressed. With a negative argument it instead tests whether a specific key is currently held down. |
INKEY$INK. | INKEY$(<number>)Waits up to the given number of centiseconds for a key and returns it as a string, or an empty string if none was pressed; INKEY$(0) is the non-blocking form used for game input. |
INPUTI. | INPUT [<prompt>,] <var>[, <var>]…Reads typed values into one or more variables, displaying an optional prompt string and a "?" prompt; commas separate multiple values and INPUT halts the program until Return is pressed. |
INSTRINS. | INSTR(<string>, <string>[, <start>])Returns the position of the second string within the first (1-based), or 0 if not found; an optional third argument sets the starting position for the search. |
INT | INT(<number>)Returns the integer part of a number, rounding towards minus infinity (so INT(-2.5) is -3). |
LEFT$LE. | LEFT$(<string>, <length>)Returns the leftmost n characters of a string (the whole string if n exceeds its length). |
LEN | LEN(<string>)Returns the number of characters in a string. |
LET | LET <var> = <number> | <string>Assigns a value to a variable. LET is optional in BBC BASIC, so the keyword is rarely written out. |
LINELIN. | INPUT LINE <strvar>A modifier for INPUT: INPUT LINE reads a whole line of text into a string variable, including commas, spaces and leading punctuation that plain INPUT would treat as separators. |
LISTL. | LIST [<line>[, <line>]]Lists the program, optionally restricted to a line range; the LISTO setting controls indentation of structured loops. |
LN | LN(<number>)Returns the natural (base-e) logarithm of a positive number. |
LOADLO. | LOAD <filename>Clears the current program and loads a tokenised BASIC program from the filing system, leaving variables cleared. |
LOCALLOC. | LOCAL <var>[, <var>]…Inside a DEF PROC or DEF FN, declares variables local to that routine, saving and restoring their previous values around the call so recursion works correctly. |
LOG | LOG(<number>)Returns the base-10 logarithm of a positive number. |
LOMEMLOM. | LOMEM | LOMEM = <number>A pseudo-variable giving the address of the bottom of BASIC variable storage; it can be reassigned to move where variables are kept (normally just above the program). |
MID$M. | MID$(<string>, <start>[, <length>])Returns a substring starting at the given 1-based position; without a length it returns the rest of the string from that point. |
MOD | <number> MOD <number>Integer remainder after division (the companion of DIV); the result takes the sign of the dividend. Operands are converted to integers first. |
MODEMO. | MODE <mode>Selects a screen mode (0–7 on the Micro; the Master adds shadow modes 128–135 and extra modes), clearing the screen and resetting graphics. MODE 7 is teletext; higher-resolution modes consume more RAM. |
MOVEMOV. | MOVE <x>, <y>Moves the graphics cursor to the given coordinates without drawing, setting the start point for the next DRAW or PLOT. |
NEW | NEWErases the current program by resetting BASIC pointers; the text remains in memory, so OLD can usually recover it if NEW was a mistake. |
NEXTN. | NEXT [<numvar>]Marks the end of a FOR loop and returns to it if more iterations remain; naming the counter variable lets a single NEXT close several nested loops at once. |
NOTNO. | NOT <number>Returns the bitwise complement (one's complement) of an integer. Because TRUE is -1 and FALSE is 0, NOT also inverts a logical value. |
OFFOF. | OFFA keyword that switches a feature off when it follows another statement, e.g. TRACE OFF to stop line tracing or ON ERROR OFF to disable an error handler. |
OLDO. | OLDRecovers a program after an accidental NEW (or soft reset), provided no new program text has been entered over it. |
ON | ON <number> GOTO <line>[, <line>]… | ON <number> GOSUB <line>[, <line>]… | ON ERROR <statement>Computed branch: ON n GOTO/GOSUB jumps to the nth line number in the list, and ON ERROR installs an error handler. An optional ELSE clause handles an out-of-range index. |
OPENINOP. | OPENIN(<filename>)Opens an existing file for reading and returns a channel number for use with BGET#, INPUT# and CLOSE#. Returns 0 if the file cannot be found. |
OPENOUTOPENO. | OPENOUT(<filename>)Creates a new file (or truncates an existing one) for writing and returns a channel number for use with BPUT#, PRINT# and CLOSE#. |
OPENUPOPENU. | OPENUP(<string>)Opens an existing file for both reading and writing (random access) and returns a channel number. Returns 0 if the file does not exist. |
OR | <number> OR <number>Bitwise/logical OR of two integers. Acts as a logical OR in conditions since any non-zero (true) operand contributes set bits. |
OSCLIOS. | OSCLI <string>Passes a string to the operating-system command-line interpreter (the same as a * command), letting commands be built at run time from variables. |
PAGEPA. | PAGE | PAGE = <number>A pseudo-variable holding the address where the BASIC program text begins; it can be read or assigned to relocate the program. Usually &E00 on a Model B. |
PI | PIThe constant π, approximately 3.14159265. |
PLOTPL. | PLOT <action>, <x>, <y>The general graphics primitive: the first argument selects an action (line, point, filled triangle, circle and so on) at the given coordinates. MOVE, DRAW and others are shorthands for particular PLOT codes. |
POINTPO. | POINT(<x>, <y>)Returns the logical colour of the pixel at the given graphics coordinates, or -1 if the point lies outside the screen. |
POS | POSReturns the current text cursor column (0 at the left edge); pair with VPOS for the row. |
PRINTP. | PRINT [TAB(<col>[, <row>])] [<expr>][;|,|']…Outputs numbers and strings to the screen; "," tabs to the next field, ";" suppresses the trailing newline and column spacing, and "'" forces a newline. The @% variable controls numeric formatting. |
PROCPRO. | PROC<name>[(<arg>[, <arg>]…)]Calls a user-defined procedure created with DEF PROC, optionally passing arguments; execution returns to the statement after the call when ENDPROC is reached. |
PTRPT. | PTR#<file> | PTR#<file> = <number>Reads or sets the sequential byte pointer of an open file, allowing random access; assigning to it seeks to a given offset from the start of the file. |
RADRA. | RAD(<number>)Converts an angle from degrees to radians. |
READREA. | READ <var>[, <var>]…Reads the next item(s) from DATA statements into variables, advancing the DATA pointer; RESTORE resets where reading resumes. |
REM | REM <comment>Marks the rest of the line as a comment that BASIC ignores. Comments still occupy program memory. |
RENUMBERREN. | RENUMBER [<line>[, <number>]]Renumbers the whole program and fixes up GOTO/GOSUB targets, starting at the given line and stepping by the given amount (defaults 10, 10). |
REPEATREP. | REPEATMarks the top of a REPEAT…UNTIL loop, whose body always runs at least once and repeats until the UNTIL condition becomes true. |
REPORTREPO. | REPORTPrints the text message of the most recent error, typically used within an ON ERROR handler alongside ERR and ERL. |
RESTORERES. | RESTORE [<line>]Resets the DATA read pointer so the next READ starts again from the first DATA statement, or from the DATA on the given line if one is supplied. |
RETURNR. | RETURNReturns from a GOSUB to the statement following the call. |
RIGHT$RI. | RIGHT$(<string>, <length>)Returns the rightmost n characters of a string (the whole string if n exceeds its length). |
RNDRN. | RND[(<number>)]Returns a random number: RND(n) gives an integer from 1 to n, RND(1) gives a real between 0 and 1, bare RND gives a random 32-bit integer, and RND(0) repeats the last RND(1) value. A negative argument reseeds the generator. |
RUNRU. | RUNClears variables and runs the current program from its first line. |
SAVESA. | SAVE <filename>Saves the current tokenised BASIC program to the filing system under the given name. |
SGNSG. | SGN(<number>)Returns the sign of a number: -1 if negative, 0 if zero, 1 if positive. |
SINSI. | SIN(<number>)Returns the sine of an angle given in radians. |
SOUNDSO. | SOUND <channel>, <amplitude>, <pitch>, <duration>Plays a note on one of four sound channels: arguments are the channel, amplitude (0 to -15, or an envelope number), pitch (0–255), and duration in twentieths of a second. |
SPCSP. | SPC(<number>)Used within PRINT or INPUT to output the given number of spaces. A convenient way to pad output without building a string. |
SQRSQ. | SQR(<number>)Returns the square root of a non-negative number. |
STEPS. | FOR <numvar> = <number> TO <number> STEP <number>Optional part of a FOR statement that sets the increment added to the loop counter each pass; the step may be negative or fractional. Defaults to 1 when omitted. |
STOPSTO. | STOPHalts the program and reports "STOP at line n", chiefly for debugging; unlike END it produces an error-style message. |
STR$STR. | STR$(<number>)Converts a number to its string representation, using the current @% print format; prefix with ~ (STR$~) for a hexadecimal result. |
STRING$STRI. | STRING$(<length>, <string>)Returns a string made of the given string repeated n times - handy for drawing rules or padding output. |
TABTAB. | TAB(<col>[, <row>])Within PRINT, TAB(x) moves to text column x on the current line, while TAB(x,y) moves the cursor to column x, row y (origin top-left). Only valid inside PRINT/INPUT. |
TANT. | TAN(<number>)Returns the tangent of an angle given in radians. |
THENTH. | IF <number> THEN <statement> | <line>Follows the condition in an IF statement and introduces the action taken when it is true; a bare line number after THEN is treated as a GOTO. |
TIMETI. | TIME | TIME = <number>A centisecond elapsed-time counter (100 per second) that can be read and assigned, commonly used for frame pacing and timing loops. |
TO | FOR <numvar> = <number> TO <number>Separates the start and limit values in a FOR statement, setting the value the loop counter runs up (or down) to. |
TRACETR. | TRACE ON | TRACE OFF | TRACE <line>Turns line-number tracing on or off for debugging, printing each line number in braces as it runs; TRACE n traces only lines below number n. |
TRUETRU. | TRUEThe constant -1, the value BASIC returns for a true condition (all bits set). |
UNTILU. | UNTIL <number>Marks the end of a REPEAT loop; the loop repeats until the condition is true (non-zero). |
USRUS. | USR(<addr>)Calls a machine-code routine at the given address with the registers preset from A%, X%, Y% and the carry flag, and returns the resulting register values packed into one number. |
VALVA. | VAL(<string>)Returns the number at the start of a string, reading as many leading digits as form a valid number and stopping at the first non-numeric character (0 if none). |
VDUV. | VDU <byte>[, <byte>]…Sends raw bytes to the VDU (screen) driver to perform operations like setting colours, defining characters (VDU 23) or window areas; a trailing semicolon sends a value as two bytes (a 16-bit word). |
VPOSVP. | VPOSReturns the current text cursor row (0 at the top); pair with POS for the column. |
WIDTHW. | WIDTH <number>Sets the print line width so output wraps to a new line after that many characters; WIDTH 0 disables the automatic wrap. |
Argument notation
Anything in <angle brackets> is a value you supply; everything else is typed exactly as shown. [square brackets] mark an optional part, | separates alternatives, and … means the part before it can repeat. The arguments on this page are:
<number>- a numeric expression
<string>- a string expression
<expr>- a value of either type, where the keyword takes both
<byte>- a value from 0 to 255
<constant>- a literal number or string, not an expression
<var>- a variable of either type
<numvar>- a numeric variable
<strvar>- a string variable
<line>- a line number
<statement>- one BASIC statement
<comment>- free text, to the end of the line
<name>- a name the program defines for a function or procedure
<param>- a parameter, where the definition introduces it
<arg>- a value, where the call passes it
<start>- the position something starts at, counting from 1
<length>- how many characters
<x>- a horizontal graphics coordinate
<y>- a vertical graphics coordinate
<col>- a text column
<row>- a text row
<mode>- a screen mode
<action>- which of several things the keyword should do
<colour>- a colour, by number
<channel>- a sound channel
<pitch>- how high a note sounds
<duration>- how long a sound lasts
<envelope>- an envelope, by number
<prompt>- text shown before the input; a literal, not an expression
<file>- an open file, by the number it was opened on
<filename>- the name of a file on tape or disc
<addr>- a memory address
<amplitude>- how loud a note sounds
Showing 136 of 136 keywords