Sinclair BASIC


Sinclair BASIC is a dialect of the programming language BASIC used in the 8-bit home computers from Sinclair Research and Timex Sinclair. The Sinclair BASIC interpreter was made by Nine Tiles Networks Ltd.

History

Sinclair BASIC was originally developed in 1979 for the ZX80 by Nine Tiles. The programmers were John Grant, the owner of Nine Tiles, and Steve Vickers.
It was initially an incomplete implementation of the 1978 American National Standards Institute minimal BASIC standard with integer arithmetic only, termed the 4K BASIC for the ZX80. It evolved through the floating-point 8K BASIC for the ZX81 and TS1000, and became an almost complete version in the 16 KB ROM ZX Spectrum. It is present in all ZX Spectrum compatibles.
As of 2015, interpreters exist for modern operating systems, and older systems, that allow Sinclair Basic to be used easily.

Syntax

New BASIC programmers might start with a simple program, perhaps using the language's PRINT statement to display a message on the screen; a well-known and often-replicated example is Kernighan and Ritchie's Hello world program:

10 PRINT "Hello, World!"

Keywords

On the 16K/48K ZX Spectrum, there are 88 keywords in Sinclair BASIC, denoting commands, functions and logical operators, and other keywords :
KeywordParametersEntered usingTypeSummary
ABSnumber then FunctionReturns the absolute value of number
ACSnumber then FunctionReturns the arccosine of number
ANDLogical operatorReturns true if both conditions on either side of the AND keyword are true, else returns false
ASNnumber then FunctionReturns the arcsine of number
ATline, column;OtherUsed in a PRINT statement to print at the line and column specified; for example, PRINT AT 5,10;"*" puts a star in column 10 of line 5.
ATNnumber then FunctionReturns the arctangent of number
ATTR then FunctionReturns a byte containing information on the colours of the text cell on the screen, corresponding to the specified line and column;note that, unlike most Sinclair BASIC keywords, the parentheses are required; the first three bits indicate the ink colour, the fourth, fifth and sixth bits the paper colour, the seventh bit whether the colours are bright or not, and the eight, whether they are flashing
BEEPduration, pitch then CommandProduces sound from the computer's speaker; duration is in seconds, pitch is in semitones above or below middle C
BINnumber then OtherIndicates number is in binary notation
BORDERnumberCommandSets the outer border of the screen to the colour specified by the number
BRIGHTnumber then Command/otherMakes all following colours brighter if number is 1, or its normal shade if 0
CATnumber then CommandDisplays contents of ZX Microdrive specified by number
CHR$number then FunctionReturns the character corresponding to the decimal number in the computer's character set
CIRCLEx, y, r then CommandDraws a circle with its centre at coordinates and radius r
CLEARaddressCommandClears the screen, all variables and the GO SUB stack, and optionally sets the maximum RAM address to be used by BASIC
CLOSE #number then CommandCloses the specified stream number for access
CLSCommandClears all text and graphics from the screen
CODEstring then Function/otherReturns the number corresponding to the first character in string in the computer's character set; also used to save arbitrary chunks memory to tape, disk, etc. and load them back in — see LOAD, SAVE and VERIFY for details
CONTINUECommandRestarts a program after it has stopped due to an error or the user pressing the or keys
COPYCommandSends the currently displayed screen to the printer
COSnumber then FunctionReturns the cosine of number
DATAcomma-separated values then Command/otherProvides numbers and/or strings to use with the READ command and allows saving the contents of an array to tape when used with the SAVE command
DEF FNname = operation then CommandDefines a custom function that can be used with the FN command;function definitions must be of the form f=operations, for example f=x*2 and the function name may not consist of more than one letter, plus a $-symbol if the function returns a string
DIMvariableCommandDeclares an array with the specified dimensions, which may be multi-dimensional ; if used with strings, the last dimension indicates the length of each of the strings is an array of two strings each of five characters long, and DIM b$
DRAWx, y CommandDraws a line in the current INK colour to coordinates from the coordinates used by the previous PLOT or DRAW command; if the optional r is supplied, it indicates the radius of the circle segment to be drawn, in radians
ERASEdrive;"filename" then CommandDeletes the specified file from a ZX Microdrive
EXPnumber then FunctionReturns e to the power number
FLASHnumber then Command/otherMakes all following text alternate its foreground and background colours
FNfunction then FunctionCalls the function defined earlier in the program using DEF FN
FORMATdrive;"name" then CommandFormats the cartridge in the indicated Microdrive and assigns it the identifier name
FORvariable = start TO endCommandStarts a FOR-NEXT loop; the variable name may only be one character long
GO SUBnumberCommandMakes the program jump to the BASIC line specified by number; when the program encounters the command RETURN, it will jump back to the statement after the GO SUB
GO TOnumberCommandMakes the program jump to the BASIC line specified by number
IF condition THENCommandEvaluates the condition, and if true, executes the statement that follows the keyword THEN that must come after the condition, for example IF a=1 THEN LET b=2
INaddress then FunctionReturns a byte read from the hardware input/output port corresponding to the address
INKnumber then Command/otherSets the foreground colour for text and graphics
INKEY$ then FunctionReturns a string representing the key being pressed on the keyboard at the moment the function is called, or an empty string if none is, but does not wait for a keypress
INPUT variableCommandHalts program execution until the user types in something on the keyboard and presses the Enter key, then stores the entered value in the specified variable; if the optional prompt is supplied, this will be shown on the screen
INTnumber then FunctionReturns the integer value of number, rounding down to the nearest whole number
INVERSEnumber then Command/otherReverses the colours on all following text if number is 1, so that it uses the current ink colour for the background and the current paper colour for the text, or sets them back to normal if number is 0
LENstring then FunctionReturns the number of characters in string
LETvariable=valueCommandAssigns value to the named variable
LINE then Other
  • When used in an INPUT statement before a string variable, will not put quotation marks around its prompt, for example INPUT "Name: "; LINE n$
  • When used in a SAVE statement so that when the BASIC program being saved is loaded again, it starts automatically at the line number indicated
LISTCommandOutputs the current BASIC program to the screen; if the optional number is provided, it omits all lines with a lower number
LLIST then CommandAs LIST except the listing is output to the printer
LNnumber then FunctionReturns the natural logarithm of number
LOAD"" CommandLoads a program or data into RAM from tape, ZX Microdrive, disk, etc., deleting any existing BASIC program and variables; if an empty string is provided, this loads the first program found, else it will search the tape for the program named in the string; if the optional CODE is provided, will load the program into memory at the address it had when it was saved, or at the specified address ; if the optional DATA variable is provided, will load the data from the tape into the array named variable
LPRINTtext then CommandAs PRINT except output is sent to the printer
MERGE"" then CommandAs LOAD, except it does not delete the current program and variables; if a line number exists in both, that of the newly loaded program overwrites the existing one
MOVEstream1 TO stream2 then CommandMoves data from one stream to another
NEWCommandErases the current BASIC program and all variables
NEXTvariableCommandCloses a FOR-NEXT loop; the variable must match that of the corresponding FOR command — “empty” NEXTs to refer to the immediately preceding FOR in the program are not allowed
NOTconditionLogical operatorReturns true if the condition is false, else returns false
OPEN #stream then CommandOpens a stream for reading from and/or writing to
ORLogical operatorReturns true if either of the conditions on either side of the OR keyword are true, else returns false
OUTaddress, value then Commandinput/output port] corresponding to the address
OVERnumber then Command/otherWill make following text overprint with an XOR operation what is already on the screen if number is 1, instead of erasing it, or erase it if number is 0
PAPERnumber then Command/otherSets the background colour for text and graphics
PAUSEdelayCommandHalts program execution for the specified delay, in of a second in Europe or in North America
PEEKaddress then FunctionReturns a byte representing the contents of the memory location pointed to by address
PI then FunctionReturns the value of pi
PLOTx, yCommandDraws a pixel in the current INK colour on the screen at the coordinates
POINT then FunctionReturns 1 if the pixel pointed at graphical coordinates is currently in the ink colour, else returns 0
POKEaddress, valueCommandSets the contents of address in RAM to value
PRINT textCommandPrints text to the screen; if used with AT, will print at the specified text coordinates, else in the first column of the line after that used by the last PRINT statement
RANDOMIZECommandInitializes the random number generator; if used without a number
RUNCommandStarts the current BASIC program, from its first line if no number is specified, else from the line with that number
SAVELINE number]CommandSaves the current BASIC program to tape or other storage device, with the filename specified; if the optional LINE followed by a line number is used, then the program will start automatically at the indicated line number when it is LOADed back in; with the optional DATA, the command saves the contents of the array named by the variable instead of the current BASIC program
SCREEN$ then +Function/otherAs a function, identifies the character at the specified line and column on the screen. Used after the filename in a LOAD or SAVE command, indicates that the contents of the display memory should be loaded or saved; this essentially makes it a shortcut for CODE 16384,6912 but does not work with VERIFY because the contents of the display memory will be different by the time that command reads back the saved data;
SGNnumber then FunctionReturns 1 if number is positive, 0 if it is 0, and −1 if it is negative
SINnumber then FunctionReturns the sine of number
STEPnumberOtherIndicates the interval used by a FOR statement, for example FOR n=2 TO 6 STEP 2 will skip n=3 and n=5 in the loop
STOPCommandEnds execution of the current program, exiting to the BASIC editor; can also be given when the computer is waiting for input using the INPUT command; once the program is stopped, it can be resumed with CONTINUE
SQRnumber then FunctionReturns the square root of number
STR$number then FunctionReturns the character from the computer's character set corresponding to number
TABcolumn then OtherIn a PRINT statement, makes sure that the text to be output begins in the column specified, wrapping to the next line as necessary, but never more than one line
TANnumber then FunctionReturns the tangent of number
THENstatementOtherFollows the condition in an IF statement to indicate what should happen when the condition evaluates to true
TOOtherIndicates a range from the number to the left of TO to the number of the right of it, inclusive; when used with FOR both numbers must be supplied, while if used to slice strings, either may be left off to indicate the start or end of the string
USRstring or address then FunctionWhen called with a single-character string, this returns the memory address at which the glyph for the user-defined graphic character corresponding to that character is defined. If called with an address, it starts machine code execution at that address and returns the contents of the Z80’s BC register pair.
VALstring then FunctionEvaluates the string as a number and returns the result; this can perform calculations: VAL "1+2" returns 3, for example, and also evaluates variables and even other VAL statements: LET a=1: VAL "a+VAL ""2""" also returns 3
VAL$string then FunctionSimilar to VAL but evaluates the string as a string
VERIFY"" then CommandReads a program from tape or other storage, much like LOAD, but instead of loading it into memory, compares it to the program that is currently in memory; this is intended to make sure the program, has been SAVEd correctly
In 48K models and older, the keywords are entered via Sinclair's unique keyword entry system, as indicated on the table. The most common commands need one keystroke only; for example, pressing only at the start of a line on a Spectrum produces the full command PRINT. Less frequent commands require more complex key sequences: BEEP is keyed by pressing plus to access extended mode, keeping held down and pressing. Keywords are colour-coded on the original Spectrum keyboard to indicate which mode is required:
The ZX81 8K BASIC used the shorter forms GOTO, GOSUB, CONT and RAND, whereas the Spectrum used the longer forms GO TO, GO SUB, CONTINUE and RANDOMIZE. The ZX80 4K BASIC also used these longer forms but differed by using the spelling RANDOMISE. The ZX81 8K BASIC was the only version to use FAST, SCROLL, SLOW and UNPLOT. The ZX80 4K BASIC had the exclusive function TL$; it was equivalent to the string operator in later versions.
Unique code points are assigned in the ZX80 character set, ZX81 character set and ZX Spectrum character set for each keyword or multi-character operator, i.e. <=, >=, <>, "", **. These are expanded by referencing a token table in ROM. Thus, a keyword uses one byte of memory only, a significant saving over traditional letter-by-letter storage. This also meant that the BASIC interpreter could quickly determine any command or function by evaluating one byte, and that the keywords need not be reserved words like in other BASIC dialects or other programming languages, e.g., it is allowed to define a variable named PRINT and output its value with PRINT PRINT. This is also related to the syntax requirement that every line start with a command keyword, and pressing the one keypress for that command at the start of a line changes the editor from command mode to letter mode. Thus, variable assignment requires LET. This practice is also different from other BASIC dialects. Further, it meant that unlike other BASIC dialects, the interpreter needed no parentheses to identify functions; SIN x was sufficient, no SIN needed. The 4K BASIC ROM of the ZX80 had a short list of exceptions to this: the functions CHR$, STR$, TL$, PEEK, CODE, RND, USR and ABS did not have one-byte tokens but were typed in letter-by-letter and required the parentheses. They were listed as the INTEGRAL FUNCTIONS on a label above and to the right of the keyboard.
The 128K Spectrum models, the ZX Spectrum 128, +2, +3, +2A, and +2B, also stored keywords internally in one-byte code points, but used a conventional letter-by-letter BASIC input system. They also introduced two new commands:
The original Spanish ZX Spectrum 128 included four additional commands in Spanish, one of which was undocumented. These can be translated as:
Unlike the LEFT$, MID$ and RIGHT$ functions used in the ubiquitous Microsoft BASIC dialects for home computers, parts of strings in Sinclair BASIC are accessed by numeric range. For example, gives a substring starting with the 5th and ending with the 10th character of the variable a$. Thus, it is possible to replace the LEFT$ and RIGHT$ commands by simply omitting the left or right array position respectively; for example is equivalent to LEFT$. Further, a$ alone is enough to replace MID$.

Variable names

and array variable names must consist of only one alphabetical character. Thus, LET a=5, LET Apples=5, LET a$="Hello", DIM a and DIM a$ are all good, while LET Apples$="Fruit", DIM Apples and DIM Apples$ are not.
The long variable names allowed for numeric variables can include alphanumeric characters after the first character, so LET a0=5 is allowed but not LET 0a=5. The long variable names can also include spaces, which are ignored, so LET number of apples = 5 is the same as LET numberofapples = 5

Official versions

Interpreters for the ZX Spectrum family

Several ZX Spectrum interpreters exist.
Several ZX Spectrum compilers exist.