This list is based on the Wikibooks Qbasic command list (which now uses an over aggressive filter to 'detect' non-constructive changes, thus preventing corrections)
A somewhat more comprehensive list can be found here
Note - Qbasic (and it's SHELL command) does not support long file names (everything is 8.3). So in most cases you will want to run a .cmd 'wrapper' around the QBasic .bas script to adjust the file names before/after processing. If you MUST use Qbasic 'on it's own', try these machine code SUBroutines
N = ABS(numericalValue)
Returns the 'absolute' value of a numericalValue, turning a negative to a positive (e.g. -4 to 4)
PRINT ABS(54.345) 'prints 54.345
PRINT ABS(-43.2) 'prints 43.2
N = ASC(characterOrString)
Returns the ASCII code number of the (first) character found within the brackets.
PRINT ACS("this") 'prints 116 (which is the acsii code for t)
See also CHR$()
ATN(numericValue)
The Arc-Tangent of the numericValue (in degrees) is returned
angle = ATN( B )
angle2 = ATN( 23 / 34 )
BEEP
The BIOS on the motherboard is instructed to emit a "Beep" sound from the PC 'speaker'.
See also SOUND and PLAY
CALL subroutineName (parameterList)
Control is passed to SUBroutine subroutineName. The values in the parameterList are copied to variables in the SUBroutine header.
See also DECLARE SUB
CHAIN filePathName {parameterList}
Control is passed to the specified filePathName (which is 'run' from the command line along with the parameterList). Typically filePathName will be another .bas file, a command (.bat or .cmd) script or an executable (.com, .exe) program. If the file successfully terminates, Qbasic execution continues (with the command follow the CHAIN)
The file part of filePathName must be '8.3' format (or 'escaped' in quotes)
See also ENVIRON, COMMON (use before the CHAIN command to 'share' variables between this Basic scrip and others)
See also SHELL (to invoke the DOS Command Line interpreter)
CHDIR directoryName
CHDIR changes the 'working directory', i.e. the default location of any file that is OPEN'ed or CHAIN'ed etc. The initial 'working directory' is the directory containing the QBasic.exe interpreter. The directoryName is declared exactly like in DOS PROMPT (if the directory name contains spaces, the entire name must be contained within quotes)
CHDIR "c:/Program Files/QBasic_FIles/Test Files"
See also MKDIR and RMDIR
Returns the string (character symbol) of the ASCII code value.
q$ = CHR$(34) 'sets q$ to the double quote character "
CHR$ is often used to 'load' characters into string variables when that character cannot be typed (e.g. the Esc key or the F{n} (Function Keys) or when the character would be 'recognised' and acted upon by the QBASIC interpreter (for example, the double quote ").
Typical character codes (and their 'function'):
07 Beep (same as BEEP), 08 Backspace, 09 Tab, 27 Esc, 33 Explanation mark, 34 Double quote, 72 Up Arrow, 75 Left Arrow, 77 Right Arrow, 80 Down Arrow
For more 'special' character code values, see your 'Character map' (found in Start, Programs, System Tools)
CINT(numericalValue)
Rounds the numericalValue the the 'nearest' integer. If the numericalValue exceeds the Integer limits (32767 to -32768) an error will be returned
Values greater than .5 are rounded up. Values lower than .5 are rounded down. Values of EXACTLY .5 are rounded to the nearest EVEN integer, be that up or down.
CIRCLE (X, Y), radius, colourNumber
Draws a circle, center X, Y of radius pixels in colour colourNumber on a 'graphics mode' display
See the SCREEN command for setting your display into Graphics modes.
CLEAR
Clears the contents of all variables, strings and arrays. Also closes any OPEN files.
See also CLS
CLOSE {#n}
Closes files. If used without any #n reference, all open files are closed, otherwise only the selected file is closed
'close the file that was OPEN'ed as #2
CLOSE #2
See also OPEN
CLS
Clears the active screen. Erases all text, graphics, resets the cursor to the upper left (1,1), and also applies the current background color (as set using the COLOR command) to the whole screen.
COLOR textColour{, backgroundColour}
Canges the colour of the text (and, optionally, the background) used when next 'printing' to the current output window.
'switch to red text
COLOR 4
PRINT "This red text"
'switch to yellow text on a blue background
COLOR 14, 01
PRINT "Yellow on Blue"
The colour codes are: 00: Black 08: Dark Grey 01: Dark Blue 09: Light Blue 02: Dark Green 10: Light Green 03: Dark Cyan 11: Light Cyan 04: Dark Red 12: Light Red 05: Dark Purple 13: Magenta 06: Orange Brown 14: Yellow 07: Grey 15: White
Note Only screen modes 0, 7, 8, 9, 10 support a background color. To 're-paint' the whole screen in the current background colour, use the CLS command.
COMMON SHARED variableName
Makes the variableName 'shared' (global) so it can be accessed across multiple QBasic scripts (see also the CHAIN command). Each program that declares 'variableName' as COMMON will share the same value.
NOTE. All COMMON statements must appear at the start of the program (i.e. before any executable statements).
CONST name {AS type} = expressionOrValue
Fixes the value of name so it can not be changed within the program. If expressionOrValue is a string, it must be "quoted"
AS type is only needed if the name does not end in one of the 'type suffix' values listed below
STRING $ INTEGER % LONG & SINGLE ! (or no type postfix) DOUBLE #
CONST PI AS DOUBLE = 3.14159265 'Assigns the value 3.14159265 to the name PI
CONST Ver$ = "Software version 2.1"
Typically all CONST values are declared at the beginning of a program.
DATA seriesOfDataValues
DATA defines a series of constants that can be loaded (as initial values) into variables using the READ (and RESTORE) commands. DATA statements are typically placed at the end of the program code
See also READ, RESTORE
a$ = DATE$
DATE$ is a 'system variable' that returns the current date (as held by the BIOS) in mm-dd-yyyy string format
See also TIMER
DECLARE SUB subroutinename (parameterlist) DECLARE FUNCTION functionname (parameterlist)
SUBroutines and FUNCTIONS have to be DECLARed at the start of a QBasic script.
SUBroutines are CALLed with a sequence of variables that will be copied into the parameterlist defined in the SUBroutine header (see SUB). Chnages made to values in the parameterlist are 'preserved' on RETURN
A FUNCTION typically uses the parameterlist to generate a value for functionname. On exit from the FUNCTION, the value last set for functionname is returned
DECLARE FUNCTION ival$ (fval!)
...
int$ = ival$ (somefloat!)
...
...
' convert from floating to nearest integer string w/o leading spaces
FUNCTION ival$ (fval!)
ival$ = LTRIM$(STR$(SGN(fval!) * ABS(INT(fval! + .49999))))
END FUNCTION
See also CALL, FUNCTION, SUB, EXIT
DIM declares an array (early versions of Basic required all variables to be defined, not just arrays greater than 10)
DIM ArrayName (count{,count}, ..) {AS type}
The Array name can be of any type (Integer, Double, String etc). The type can be explicitly declared (using 'AS') or intrinsically declared (by appending a special character to the name). By default, the type is single precision floating point.
AS type is required only if the ArrayName does not end in a 'type suffix' character :-
$ = STRING (max 255 characters) % = INTEGER (2 byte 16 bit signed integer, -32,768 to 32,767) & = LONG (4 byte 32 bit signed integer, -2,147,483,648 to 2,147,483,647) ! = SINGLE (4 byte floating point, 7 digits (approx 23 bits) precision, range -3.37x10^38 to 3.37x10^38) # = DOUBLE (8 byte floating point, 15 digits (approx 48 bits) precision, range -1.67x10^308 to 1.67x10^308)
See Microsoft KB73084 for more on data types
The maximum number dimensions for a DIMed array is 60 (if an array is sued without being DIMed first, the max. dimensions is 8). No array can exceed 65,535 bytes in size. Since the minimum array type is Integer (2 byte), this means the maximum array subscript value is 32,767
NOTE Early versions of QBasic did not explicitly set the contents of an array to zero (see CLEAR command)
' create a two dimensional integer array of 100 elements each of 2 components
DIM table%(100,2)
' create a string array containing 5 strings
DIM form$(5)
' create an array that contains 20 double precision floating point numbers
DIM quotient(20) AS DOUBLE
DO instructions LOOP UNTIL testCondition
The interpreter continues to execute instructions until testCondition is met (i.e. TRUE). Since test condition is evaluated at the end of the DO..LOOP, instructions will always be executed at least once
num = 1
DO
sum = 2 * num
PRINT sum;
num = num + 1
LOOP UNTIL num > 7
' prints 2 4 6 8 10 12 14, leaving num set to 8 and sum set to 14
See also EXIT DO
DO instructions LOOP WHILE testCondition
The interpreter continues to execute instructions whilst testCondition is met (i.e. TRUE). Since test condition is evaluated at the end of the DO..LOOP, instructions will always be executed at least once
num = 1
DO
sum = 2 * num
PRINT sum;
num = num + 1
LOOP WHILE num < 7
' prints 2 4 6 8 10 12, leaving num set to 7 and sum set to 12
See also EXIT DO
DRAW "lineSequenceString"
Draws a series of (1 pixel width) straight lines, starting at the current 'cursor position', in the current colour. The lineSequenceString defines the line sequence, i.e. direction (up, down etc.) and the length in pixels. The 'cursor position' is left 'pointing' to the end of the last line (to move the cursor without drawing, use PSET)
The letter in front of each pixel count is the direction (it is not case sensitive) :- U = Up E = Upper-right (i.e draw up & right at 45 degrees) D = Down F = Lower-right (i.e draw down & right at 45 degrees) L = Left G = Lower-left (i.e draw down & left at 45 degrees) R = Right H = Upper-left (i.e draw up and left at 45 degrees)
Example
SCREEN 7 'set the terminal window to graphics mode
PSET (50, 50), 4 'set the cursor position to pixel 50,50 and set the draw colour to code 4 (red)
DRAW "u50 r50 d50 l50" 'draw a series of lines from 50,50 'up' 50, then 'right' 50, then 'down' 50 and finally 'left' 50 (i.e. draw a box)
' at the end of this sequence, the cursor position returns to pixel 50,50
Note that the display is assumed to be 1:1 aspect ratio (i.e. square). A diagonal line from 0,0 to 100,100 will be 100 * root(2) = 141 pixels long. No form of 'anti-aliasing' is used
See also PSET, LINE and CIRCLE
END
Halts execution. Typically signifies the end of the program. When QBasic sees this command it usually comes up with a statement saying: "Press Any Key to Continue" - if you press any key you will be returned to the command interpreter (Qbasic.exe or cmd.exe / command.com)
ENVIRON environmentVariable = value
The environmentVariable string must contain a Command to set a DOS environment variable to a new value for the duration of the current 'session'. On exit from the QBasic.exe interpreter, the variables are reset
' add the test folder to the PATH
ENVIRON "PATH=;C:\QBASIC\TEST"
NOTE: This command may not function on all versions of MS Windows
A$ = ENVIRON$ (environmentVariable) A$ = ENVIRON$ (n%)
The first form returns the current value of the DOS environmentVariable. The second form returns the value of the nth entry in the environment variable table
' print the current PATH
PRINT ENVIRON$("PATH")' PRINT the entire table (assuming less than 100 entries)
FOR n% = 1 TO 100
env$ = ENVIRON$ (n%)
IF env$ = "" EXIT FOR
PRINT env$
NEXT N%
NOTE: This command may not function on all versions of MS Windows
EOF(n)
Returns a value indicating if the end of the file OPEN'ed as stream #n has been reached (0 indicates the end of file has not been reached, 1 if it has)
' print the text File
OPEN File.txt FOR INPUT AS #1
DO
INPUT #1, text$
PRINT text$
LOOP UNTIL EOF(1)
Note that, since the INPUT is executed before UNITIL is reached, File.txt must contain at least one line of text - if the file is empty, you will receive an 'ERROR (62) Input past end of file'.
ERASE {arrayName{, arrayName}}
Used to erase the contents of dimensioned arrays. In no arrayName is specified, all arrays are cleared, otherwise just the specified arrayName(s)
ERROR = errorNo
Sets the ERROR system variable allowing you to manually test your error handling routine. Valid errorNo are 0-255 (however 0 means 'no error'). For the list of system error numbers, see ON ERROR GOTO
Program flow makes an immediate exit from the current CASE, SUBrubroutine or a DO .. LOOP etc, without processing further instructions in that section
EXIT CASE 'Exits from the SELECT CASE, execution continues with the command directly after the END SELECT command EXIT DEF 'Exits from a DEF FN function (supports legacy 'in-line' DEF FN, use FUNCTION for future compatibility) EXIT DO 'Exits from a DO loop, execution continues with the command directly after the LOOP UNTIL/WHILE command EXIT FOR 'Exits from a FOR loop, execution continues with the command directly after the NEXT command EXIT FUNCTION 'Exits a FUNCTION procedure, execution returns to calling command (with the current value of the function name) EXIT SUB 'Exits from a SUBroutine, execution returns and continues with the command following the calling command
See also CASE, DO, FOR, FUNCTION, SUB and DECLARE
FIELD #n, charCount% AS fieldName$ {,charCount% AS fieldName$} ...
Defines individual fields within a record for a new data file OPENed as RAMDOM (and into which PUT statements will write the values). Each filed consists of a character count charCount% and a name (fieldName$)
TYPE custDetails
name AS STRING * 30
address AS STRING * 50
END TYPE
DIM cust AS custDetails
..
OPEN "FILEDAT.DAT" FOR RANDOM AS #1 LEN = 80
FIELD #1, 30 AS name$, 50 AS address$
..
cust.name = "Joe Tester"
cust.address = "192 Some Street"
record% = 1
PUT #1, record%, cust
..
See also PUT, GET
FOR variable name = start value TO end value {STEP n} instructions NEXT variable name
The variable name is set to the start value and then the instructions executed. When the NEXT statement is reached, the variable name is incremented by the STEP value (or by 1, if no STEP is specified) and compared to the end value. If the variable name is not equal to the end value, instructions are executed again.
FOR aval = 200 TO 197 STEP-1
PRINT aval;
NEXT aval
' prints 200 199 198
' on exit, aval will contain 197
Care must be taken when using STEP, since it is quite possible to 'step past' the end value with the result that the FOR loop will run 'for ever' (i.e. until the user aborts the interpreter or an error occurs), for example :-
FOR a = 200 TO 197 STEP-2 PRINT a; NEXT a
200 198 196 194 192 ... 0 -2 -4 ... -32768 ERROR overflow
See also EXIT
FUNCTION name (parameterlist) instructions name = expression {instructions} END FUNCTION
Defines a FUNCTION which returns a value (of type implicitly set by the name postfix) defined by the expression.
See also DEFINE, EXIT
GET #n, location, variablename
GET reads from the file OPENed as #n, at position location and places the value found into variablename
For a "random-access" (data) file, location is the 'record number' and variablename must match the record type (integer, float, string). For 'binary-mode' files, location is the byte position (the first byte of the file is 1) and variablename receives that byte (only) either as an integer (0-255) or character
See also PUT
GOSUB label ... label: instructions RETURN
Command processing jumps to the label specified. When the RETURN command is encountered, processing returns to the line following the GOSUB branch.
See also SUB, CALL
IF expression1 comparisonOperator expression2 THEN command {ELSE othercommand}IF expression1 comparisonOperator expression2 THEN instructions {ELSE otherInstructions} END IF
Compares the results of two expressions using the comparisonOperator. Should the comparison conditions be met, THEN instructions are executed, otherwise control passes to the ELSE (if one exists) otherwise to the statement following END IF
Valid comparisonOperators include:
= equal to
< less than (if the expressions evaluate to characters (strings), the ascii code values are compared)
> greater than (if the expressions evaluate to characters (strings), the ascii code values are compared)
<> does not equal
<= less than or equal to
>= greater than or equal to
string variable name = INKEY$
A single character is taken from the keyboard 'buffer' (place where user keyboard entry is stored waiting for the QBasic program to 'inkey' them). If the buffer is empty, "" (empty string) is returned.
in$ = "" a$ = "" PRINT "Input data, press Esc to Exit" DO in$ + in$+a$ a$ = INKEY$ LOOP UNTIL a$ = CHR$(27) 'keep reading input until chr$(27) (the ESC key) is pressed
See also INPUT
INPUT {message[,or;]} variableName
Displays the message (if any) plus (if a semi colon follows ) a question mark on the terminal window and awaits user input. Values are accepted and assigned to the variablename(s) until the [return] key is pressed. If the variablename is type numeric, and the user attempts to enter a non-numeric character (i.e. other than +, -, 0-9 or .) the user will be prompted for input again.
INPUT #n, variableName {,variableName} {,variableName} ...
A series of values are read from the specified file stream (#n) and assigned to each specified variableName in turn. Values in the file must be separated by 'delimiters' (for strings a comma ',' or [Carriage Return][Line Feed] - for numeric values 'anything' non-numeric).
If variableName is of type string, the file is read as characters until the next 'delimiter' is encountered. If variableName is of type numeric, a single numeric value is read from the file. In each case the 'input pointer' is left positioned after the 'delimiter'.
INPUT #1, a$, n
Values are read from the file that is OPEN as #1. First characters are read and assigned to a$ until a ',' (comma) or end of line delimiter is reached. If no comma or [Carriage Return][Line Feed] is encountered before the end of file, the entire file will be read into a$ (typically resulting in an 'Out of String Space' error if the character count exceeds 255/2048/4096) - this commonly occurs when attempting to 'read' text from a file created by a UNIX-like system (which use [LineFeed] without a [CarriageReturn])
Next a numeric value is read. Since the numeric value 'delimiter' is 'anything', if a number is not found immediately after a$ is input, 'everything' is ignored until at least one numeric value is found - if no number is found before the end of file is reached, an 'End of File' Error will be returned.
See also SEEK #n
See also LINE INPUT #n,
INSTR ({start%,} source$, seek$)
Starting at character position start%, returns the position the (next) occurrence of seek$ within source$, or 0 if not found. If start% is omitted, searching starts at character position 1 (i.e. the first character of source$)
Pos% = INSTR ("abcdede", "de") 'Pos% is set to 4
Pos% = INSTR (5,"abcdede", "de") 'Pos% is set to 6
Pos% = INSTR (7,"abcdede", "de") 'Pos% is set to 0
KILL pathFileName$
Kills (deletes) the specified pathFileName$ (which can include a path and the DOS wildcard characters ? and *). If the path or file name includes spaces it must be 'quoted'
' delete all temp files
KILL C:\temp\*.*
KILL "C:\my temp files\*.tmp"
LEFT$(source$,count%)
Returns the first (i.e 'left most') count% characters from source$
A$ = LEFT$("Get the start only",4) 'A$ is set to "Get "
See also RIGHT$(), MID$().
LET [variable] = [value]
Very early versions of the QBasic.exe command interpreter required use of the 'LET' command to assign values to variables
LET N = 227 / 99
LET A$="a line of simple text"
LET is no longer needed
LINE (startX, startY) - (endX, endY){, Colour}
Draws a line on the user terminal (when set to Graphics SCREEN mode) from startX, startY to endX, endY in the indicated Colour (or the last colour used)
Note. When in SCREEN 13, the Colour == the Palette number
See also SCREEN
LINE INPUT #n, stringvariable$
A 'complete' line is read from the file OPEN as stream #n and loaded into stringvariable$ (the end of line characters, [CR][LF] are not stored as 'characters'). The 'input pointer' is left pointing at the start (first character of) of the next line.
Note that, to find the 'end of line', the QBasic interpreter searches for the 'Carriage Return' + 'Line Feed' (aka [CR][LF] = 0x0D, 0x0A) characters. When reading text files created on a UNIX/LINUX systems (where 'Line Feed' 0x0A only is used to signify 'end of line'), LINE INPUT will not recognise the 'end of line' and will continue to input until the end of file is reached. For files exceeding 2k characters, the result is an "Out of String Space" Error as a$ 'overflows'. One solution is to use a text editor able to handle UNIX files to open and 'save as' before attempting to process the file using QBasic.
len = LOF(n)
Returns the (current) length of the file OPENed as n, in bytes
LPRINT value{,/; value}
Sends (prints) value(s) to the printer (LPT1(PRN) parallel) port. If QBasic discovers no printer is connected, it will halt processing with a "Device fault" Error message .
The MS-DOS 'MODE' command can be used to redirect printing from 'LPT1' to a 'serial' port (COMx) which is turn may be re-directed by Windows to a USB connected printerFor example, to redirect LPT1 to COM1, use the following command:-
MODE LPT1=COM3To cancel redirection (when finished), use the following command:-
MODE LPT1
See also PRINT
LTRIM$(stringvar$)
Trims off (removes) any leading spaces from stringvar$, such as those generated by conversion from positive numeric value to a string using STR$
' remove any leading space
val$ = LTRIM$(STR$(val))
See also STR$
sub$=MID$(source$,start%{,length%}) MID$(original$,start%{,length%}) = replacement$
In the first use, sub$ is formed source$ starting with character start% and taking length% characters (or, length% is omitted, start% to the end of source$)
In the second use, starting at position start% in original$, length% characters are replaced by replacement$. If no length% is specified, from start% to the end of source$ are replaced
See also LEFT$ RIGHT$ LEN
ON ERROR GOTO locationlabel
ERROR is s system variable that is set as each line of code is executed. If no error is encountered, ERROR remains set to 0. If an error is encountered, ERROR takes on a non-zero value and execution jumps to whatever locationlabel you set last (or, if none, execution stops and the QBasic interpreter displays the error message (see below))
Note that ERROR catches execution errors. The entire file is checked for syntax errors before execution is started
If your error handling code includes a RESUME command (which can either return control to the same point, the next statement, or any other desired label) execution can be continued
System errorno% values are as follows:
1 NEXT without FOR 39 CASE ELSE expected 2 Syntax Error 40 Variable required 3 RETURN without GOSUB 50 FIELD overflow 4 Out of DATA 51 Internal error 5 Illegal function call 52 Bad file name or number 6 Overflow 53 File not found 7 Out of memory 54 Bad file mode 8 Label not defined 55 File already open 9 Subscript out of range 56 FIELD statement active 10 Duplicate definition 57 Device I/O error 11 Division by zero 58 File already exists 12 Illegal in direct mode 59 Bad record length 13 Type mismatch 61 Disk full 14 Out of string space 62 Input past end of file 16 String formula too complex 63 Bad record number 17 Cannot continue 64 Bad file name 18 Function not defined 67 Too many files 19 No RESUME 68 Device unavailable 20 RESUME without error 69 Communication-buffer overflow 24 Device timeout 70 Permission denied 25 Device Fault 71 Disk not ready 26 FOR without NEXT 72 Disk-media error 27 Out of paper 73 Advanced feature unavailable 29 WHILE without WEND 74 Rename across disks 30 WEND without WHILE 75 Path/File access error 33 Duplicate label 76 Path not found 35 Subprogram not defined 37 Argument-count mismatch 38 Array not defined
Notes.
1) ERROR is set when execution fails, not when the code is 'read' - so, for example, a 'Divide by 0' will ERROR out before the result is assigned to a non-existent array variable or written to a non-existent file.
2) If your error handling routine does not have a RESUME statement in it (i.e. it you try to do it all with GOTOs) ERROR handling will only work once - the next ERROR will be ignored and the program ends as if you had no ON ERROR statement at all.
3) Whilst some QBasic documentation suggests 'ON ERROR RESUME NEXT' is a valid command, this is incorrect.
See also RESUME
ON PLAY(bufferlowlimit%) GOSUB location
ON PLAY allows the MIDI music buffer (which is 32 notes in size) to be 'refilled' (from the GOSUB location) each time the number of Notes falls below bufferlowlimit% (without having to 'predict' the music timing using TIMER etc)
music$ = "o3L8ED+ED+Eo2Bo3DCL2o2Ao3L8ED+ED+Eo2Bo3DCL2o2Ao3L8ED+ED+Eo2Bo3DCL2o2A"
' go refill when less than 3 notes remaining
ON PLAY(3) GOSUB nextTune
...
...
' enable MIDI music, play in background mode (see note 1)
notePtr% = 1
musicLen% = LEN(Music$)
PLAY ON
PLAY "MBo3L8ED+ED+Eo2B"
...
...
' arrive here when buffer has less than 3 notes remaining (ie. 2, 1 or none)
nextTune:
' fill the buffer with (a maximum of) 30 new notes
IF notePtr% < musicLen% THEN
PLAY MID$(Music$, notePtr%, 30)
notePtr% = notePtr% + 30
ELSE
'tune done, stop play (or start next tune, or loop this tune etc)
PLAY OFF
END IF
RETURN
Notes.
1. In the above you must 'start the buffer count' by setting MB (Music Background) mode, otherwise the ON PLAY .. GOSUB will never 'execute' (PLAY defaults to foreground mode). See PLAY
2. If you try to add more notes than there is free buffer space, execution halts whilst the enough notes are 'played out' of the buffer to make room for all the new ones
3. Although music will continue to play (from the buffer) whilst the QBasic interpreter is awaiting user INPUT, the ON PLAY subroutine will not execute until the user INPUT is 'complete'.
See also PLAY
See similar commands ON ERROR, ON TIMER
ON TIMER(elapsed%) GOSUB location n = TIMER
The TIMER is running in the background counting in 100th's of a second. When TIMER 'event trapping' is set to ON (TIMER ON), after each elapsed% seconds count (range 1 - 86,400 i.e. 24 hours), control is passed to location.
In the second form, the current count is returned (to 2 decimal places)
ON TIMER (60) GOSUB minTick
...
TIMER ON
...
...
minTick:
BEEP
RETURN
WARNING event trapping is suspended during i/o. So, for example, whilst waiting for user INPUT no GOSUB's can occur (if the elapsed% time is exceeded whilst waiting for user INPUT, a single GOSUB will occur after the user hits the return key - other (multiple) elapsed% time-outs are lost)
See also TIME$
OPEN fileName {FOR mode} {ACCESS access} {shareMode} AS #n {LEN=recLen%}
fileName path / file name (quoted if either contain spaces) mode APPEND = the file pointer is set to the end of the file (PRINT # / WRITE # adds to the file). BINARY = access will be direct to a byte position within the file using GET or PUT statements INPUT = the file will be read sequentially using INPUT #, or LINE INPUT # statements OUTPUT = a new (empty) file is opened for sequential output (any that exists of same name is replaced) RANDOM = the file is opened for random-access, the file pointer is set to the start access READ, WRITE, or READ WRITE access limited shareMode SHARED, LOCK READ, LOCK WRITE, LOCK READ WRITE (when in a network environment) n A free data stream number 1-9 recLen% 'Record' length (in bytes) for random access files (default is 128) (for sequential access mode, recLen% specifies the buffer size, default 512)
' append to an existing log file
OPEN "C:\QBASIC\TOTAL.LOG" FOR APPEND AS #8' create a new log file
OPEN "C:\QBASIC\MAKE.LOG" FOR OUTPUT AS #9
WARNING. When you OPEN a file 'FOR OUTPUT', any existing file of the same name is deleted without warning
PALETTE palettenumber, requiredcolour
For VGA (SCREEN mode 13) only, sets the Palette entry to a new RGB color. The palettenumber must be in the range 1-256. The requiredcolour is a LONG integer created from the sum of (required Blue * 65536) + (required Green * 256) + required Red.
PAINT (xstart,ystart),{fillcolour/fillpartturnstring$},boundarycolor {,background$}
Flood fills an area with a specified fillcolour or fillpartturnstring$ pattern. Painting starts at pixel position xstart,ystart and 'floods' outwards in all directions until boundarycolor is encountered. background$ allows over-painting of pixels in boundarycolor that are (part of) a previous fillpartturnstring$ paint.
fillpartturnstring$ consists of a series of 1 byte values (each defining an 8 bit patturn) up to 64 bytes long. Each 'bit' set to 1 results in a corresponding pixel being 'painted' (0 means left alone). background$ is a single 8 bit patturn value.
' draw a circle
CIRCLE (100, 100), 75, 1
' fill it in
PAINT (100, 100), 2, 1
PLAY "notestring$"
The values in notestring$ are used to play a musical score using the MIDI method (all modern computer motherboards with built-in sound support MIDI). The notes are indicated by letters a through g (case insensitive). Accidentals are indicated with a "+" or "#" (for sharp) or "-" (for flat) immediately after the note letter. There are also codes that set the duration, octave and tempo. PLAY ignores white spaces within notestring$
PLAY "C C# C C#"
The control values are listed below :-
Ln Sets the length of the following notes. L1 = whole note, L2 = half note, L4 = quarter etc. (L8, L16, L32, L64, ...). By default, n = 4. For triplets and quintets, use L3, L6, L12, .. and L5, L10, L20, .. respectively. L can be sued to set the 'defualt' and the number added after the note in a 'shorthand' approach (eg. "L4 CDE L8 FG L4 AB" can be shortened to "L4 CDE F8G8 AB" - the numbers after F and G mean they play as eighth notes while the rest default to the L4 set quarter). On Sets the current octave. Valid values for n are 0 through 6. An octave begins with C and ends with B. (Remember that C- is equivalent to B). < > Changes the current octave respectively down or up one level. Nn Plays a specified note in the seven-octave range. Valid values are from 0 to 84. (0 is a pause.) Cannot be used with sharp / flat or 'shorthand' approach. MN means Music Normal. Note duration is 7/8ths of the length indicated by Ln. It is the default mode. ML means Music Legato. Note duration is full length of that indicated by Ln. MS means Music Staccato. Note duration is 3/4ths of the length indicated by Ln. Pn Causes a silence (pause) for the length of note indicated (same timing as Ln). Tn Tempo. Sets the number of "L4"s per minute, from 32 to 255. The default value is T120. . When placed after a note, causes the duration of the note to be 3/2 of the set duration. (i.e. for "dotted" notes. "L4 C#." would play C sharp as a dotted quarter note). Can be used for a pause as well. MB MF Stand for Music Background (see note 1) and Music Foreground. MB places a maximum of 32 notes in the music buffer and plays them while executing other statements. MF switches the PLAY mode back to normal. Default is MF.
Note 1. The maximum length of a string is 255 characters and the MB buffer 32 notes. This means it's quite possible to PLAY a string in 'Background' mode that exceeds 32 notes. If you do so, execution will stop at the PLAY command whilst the 'excess' notes are played out.
To avoid having to 'predict' buffer refill timing (using TIMER), see the ON PLAY command
For more information on using MIDI with QBasic, see Petes QB site
PRINT variable {,/; variable} {,/; variable} .. {,/;}
Displays text on the screen. variable can be anything (text is evaluated unless quoted i.e. PRINT 2+2 will print 4, PRINT ""+2" will print 2+2). If a comma is used between variables, the PRINT auto tabs to the next 8 column position before printing. If a semi-colon is used, no tab takes place. If the PRINT statements ends with a comma or semi-colen, the next PRINT continues from the position the last finished - otherwise the next PRINT starts on a new line
See also PRINT #n
See also PRINT USING
PRINT, USING formatstring; variblelist
The formatstring controls how the variblelist values appear when printed. Typically sued to 'line' up data by adding leading zero's etc. For example:-
' print the value of n% (0 - 999) with leading zeros
IF n% > 99 THEN PRINT #1, USING "###"; n%; ELSE IF n% > 9 THEN PRINT #1, USING "0##"; n%; ELSE PRINT #1, USING "00#"; n%;
PRINT #n, variable {,/; variable} {,/; variable} .. {,/;}
'Prints' (writes) the variable value(s) to the file that is OPENed as #n (instead of displaying them on the console terminal)
PSET ([X coordinate],[Y coordinate]), [Pixel Colour]
This command displays pixels, either one at a time or a group of them at once. For the command to work, the program must have a SCREEN command in it.
PUT #n, location, variablename
PUT writes to the file OPENed as #n, at position location and places the value variablename at that position
For a "random-access" (data) file, location is the 'record number' and variablename must match the record type (integer, float, string). For "binary-mode" files, location is the byte position (the first byte of the file is 1) and, to avoid byte order issues, variablename should be a single character
See also FIELD, GET
READ variable DATA value{,value}{,value}{,value}{,value}
The READ command is used to initialise variable(s) by loading them with the value(s) defined in the DATA list. Often used to load translated string data or small bitmap images (logos). A commas is sued to separate successive values (to embed a comma within a string, enclose the string in quotes)
The DATA statement(s) are traditionally placed at the end of the program (after executable code).
REM {comments} ' {comments}
When the interpreter encounters REM or " ' " (a single quote) at the start of a line, the rest of the line is ignored
RESUME {NEXT / lineLabel}
Allows execution to continue following an ERROR.
no parameter Execution returns to the line causing the ERROR and executes it again NEXT Execution continues with the line following the line causing the ERROR lineLabel Execution continues from the indicated lineLabel location
See also ON ERROR GOTO
RETURN
Control exits from a SUBroutine and execution continues with the statement following the original subroutine CALL / GOSUB statement
See also CALL, GOSUB
SCREEN ScreenMode
Sets the users 'terminal window' to a new ScreenMode.
SCREEN 0: Textmode, cannot be used for graphics.
SCREEN 1: 320 x 200 Resolution. Four Colours
SCREEN 2: 640 x 200 Resolution. Two Colours (Black and White)
SCREEN 7: 320 x 200 Resolution. Sixteen Colours
SCREEN 8: 640 x 200 Resolution. Sixteen Colours
SCREEN 9: 640 x 350 Resolution. Sixteen Colours
SCREEN 10: 640 x 350 Resolution. Two Colours (Black and White)
SCREEN 11: 640 x 480 Resolution. Two Colours
SCREEN 12: 640 x 480 Resolution. Sixteen Colours
SCREEN 13: 320 x 200 Resolution. 256 Colours. (Recommended)
Note. In SCREEN 13 you have a colour Palette of 256 colours. The PALETTE is pre-set by Windows however you can change the RGB values using the PALETTE command.
pos = SEEK #n SEEK #n, readwritePosn
#n is the OPENed file number. In the first usage, the SEEK function returns the current 'file pointer' position i.e. position of the next read or write.
In the second usage, the current 'file pointer' is reset to readwritePosn - for random-access files, readwritePosn = a record number, for other files, readwritePosn = the byte position relative to the beginning of the file (the first byte is position 1)
' restart at the beginning of the file
SEEK #1, 1
SELECT CASE [control value] CASE [case value]: {commands} CASE [case value]: {commands} .. CASE ELSE {commands} END SELECT
The control value is compared to each case value in turn. When (if) a match is found, the commands are executed. Note that, unless EXIT CASE is found, comparison then continues (i.e. if an additional 'match' is found, those commands will also be executed) until the 'CASE ELSE' is reached.
If no match is found, the CASE ELSE commands are executed
See also EXIT CASE
SGN (expression yielding a numeric value)
Yields the 'sign' of a value, -1 if < 0, 0 if 0, 1 if > 0
SHELL {commandstring$}
SHELL transfers control to a DOS 'command prompt'. If commandstring$ is present, it is executed and, on completion, control automatically returned to the QBasic program. If no commandstring$ is present, the DOS prompt is displayed (for manual command input) - to return to the QBasic program, use the EXIT command
WARNING. The maximum length of commandstring$ is 124 characters. If you exceed this, you get a 'Invalid Function Call' error (one way to reduce the length of a command that includes long file directory paths is to change the 'working directory' first - see CHDIR - or add the locations of .exe files to the DOS PATH 'environment variable')
SLEEP [n]
Execution is suspended for n seconds
SOUND frequency, duration
Generates a pure sine wave tone from the PC speaker. The frequency is from 37 to 32767 Hz. The duration is defined in terms of 'click ticks' (the default is 18.2 ticks per second)
' generate 200Hz for 10 seconds
SOUND 200, 182
See also PLAY
STR$(numnericexpression)
Converts the value of numnericexpression into a sequence of text (string) characters
valu$ = STR$(expression yielding a numeric value)
WARNING. If the result is positive, a leading 'space' is added !
Thus STR$(123) = " 123" (and not "123" as might be expected). If the result is negative, instead of a space you get a '-' (minus sign), i.e. STR$(-123) = "-123" (and not " -123" as might be expected from the positive behaviour)
See also CHR$ (for converting an ascii value into a string character) See also LEFT$, MID$, RIGHT$ (for extracting sub-strings from a line of text)
Terminates execution of the .BAS script and exits from the QBasic.exe interpreter. Control passes back to the Command Window c:\ prompt (or next line of a calling .cmd script etc.).
val = TIMER
Returns the current (free-running) time count (100ths of a second)
See also ON TIMER, TIME$
caps$ = UCASE$(mixedcase$)
Converts all alphabetic characters the mixedcase$ string to all uppercase characters (i.e. a..z --> A..Z)
See also LCASE$()
numb = VAL(characterstring$)
The executes the contents of characterstring$ as an arithmetic formula and returns a numeric value. If numb is of type INTEGER, the VAL returned is 'rounded down'.
A$ = "2 + 3" B = VAL(A$) PRINT B 'the value '5' is printed
See also STR$
WHILE {NOT} testcondition instructions WEND
The testcondition is evaluated and if true (or NOT true) the instructions are executed until WEND is reached, at which point control passes back to the WHILE line.
' copy the file open as #1 to the file open as #2
WHILE NOT (EOF(1))
LINE INPUT #1, A$
PRINT #2, A$
WEND
WRITE #n%, expressionlist
WRITES a line of values as defined by the variables in the expressionlist to the file OPENed as #n. Commas are added between items and quotation marks are added around strings (which means WRITE writes values to a file in a form that can be read by the INPUT command)
See also INPUT
Clicking "Next >>" (in the Navigation menu, left) takes you to ...