TERNS A\ rO\D T O\S OF SA-! A+D .CEZSE OF TAhDV COMP-TER EO, PNEhT A40 SOF-;\AQF J.RCnASE3 F33V 7AC 0 SnACI( :3VPA\'-OhhED COVP-TER CEhTERS RETA j-?RE? A\? >A0 S SrAC< F9A\Cn SEES 'IR 2EA-E;IS AT TnE R A-TnOR ZEC -0CAT OhS LIMITED WARRANTY CUSTOMER OBLIGATIONS A CUSTOMER assumes full responsibility that this computer hardware purchased (the Equipment and any copies of software included with the Equipment or licensed se arately (the Software ) meets the specifications capacity capabilities versatility and other requirements of CUETOMER 6 CUSTOMER assumes full responsibility lor the condAon and effectiveness of the operating environment in whlch toe Equipment and Software are to function and lor its installation LIMITED WARRANTIES AND CONDITIONS OF SALE A For a period of ninety (901 calendar days lrom the date of the Radio Shack sales document received upon purchase of the Equipment RADIO SHACK warrants to the original CUSTOMER that the Equipment and the medium upon which the Software is stored is free from manufacturing defects This warranty is only applicable lo purchases of Tandy Equipment by the original customer from Radlo Shack company-owned computer cenlers retail stores, and Radlo Shack franchisees and dealers at their aulhorlzed locations The warrantv is

111.

6 9ADIO SPACK sha I not be liable for any damages caused by delay in delivering or furnishing Equipment and or Softviare C No actio1 ar sin out of any claimed breach of this Warranty or transactions under this Warranty may be brought rr'ore than two 92) years after the cause of action has accrued or more than four (4) years after the date of the Radio Shack sales document for the Equlpment or Software whichever first occurs D Sore states do not a1 ow the imitat on or exclusion of incidental or coiseouential damages so the above imitationis) or exclusionls) may lot apply to CUSTOMER IV. SOFTWARE LICENSE RADIO SHACK grants to CUSTOMER a non exclusive paid up license to use the TANDY Software on one computer subject to the following provisions A Except as otherwise provided in this Software License applicable copyright laws shall apply to the Software B Title to the medium on Nhich the Software is recorded (cassette and or diskette) or stored IROMi is transferred to CLSTOMER but not t'tle to the Software C CLSTOMER may use Software on a multiuser or network system only if eit'ler the Software is expressly labeled to be for use on a multiuser or network system or one copy of th s software is purchased for each node or terwiial on wh ch Software s to be used simultaneously D CUSTOMER shal, not use make manufacture or reproduce copies of Software except for use on one computer and as is specifically provided in this Software License Customer is expressly prohibited from disassembling the Software E CUSTOKER s perwitted to make additional copies of the Software only for backup or archival purposes or If additional copies are required in the operation of one computer with the Software but only to the extent the Software allows a backup copy to be made However for TRSDOS Software CUSTOMER is permitted to make a lim ted number of additionas copies for CUSTOMER S own use F CLSTOMER may resell or distribute unmodified copies of the Software provided CUSTOMER has purchased one copy of the Software for each one soid or distributed The provisions of this Software License shall also be applicable to third parties receving copies of the Software from CUSTOMER C All copyright notices s+al' be retained on all copies of the Software V. APPLICABILITY OF WARRANTY A T9e term and conditions of this Warranty are applicable as between RADIO SHACK and CLSTOMER to either a sale of the Equipment and or Software License to CUSTOMER or to a transaction whereby Radio Slack sells or conveys such Equipment to a third party lor lease to CUSTOMER 6 The imitations of liabil ty and Warraity provisions herein sha I nure to the benefit of RADIO SHACK the author owner and or licensor of the Software and any manufacturer of the Equipment sold by Radio Shack VI. STATE LAW RIGHTS The warranties granted herein give the original CUSTOMER specific legal rlghts and 1% original CUSTOMER may have other riglts which vary from state to state 8 85

GW '"-BASIC Software: Copyright 1983, 1984 Corpora- tion. Licensed to Tandy Corporation. All Rights Reserved. MS"'-DOS Software: Copyright 1981, 1982, 1983 Microsoft Cor- poration. Licensed to Tandy Corporation. All Rights Reserved. Tandym 1000 BIOS Software: Copyright 1984 Tandy Corporation and Phoenix Compatibility Corporation. All Rights Reserved. BASIC Reference Manual: Copyright 1985 Tandy Corporation. All Rights Reserved. MS and GW are trademarks of Microsoft Corporation. Tandy is a registered trademark of Tandy Corporation. Reproduction or use without express written permission from Tandy Corporation, of any portion of this manual is prohibited. While reasonable efforts have been taken in the preparation of this manual to assure its accuracy, Tandy Corporation assumes no liability resulting from any errors in or omissions from this manual, or from the use of the information contained herein.

10 9 8 7 6 5 4 3 2 Contents

Introduction to BASIC 7 About this Manual 7 Notations 7 Terms 8 Chapter 1 / About BASIC for MS-DOS 11 Disk Files 11 Pathnames 12 Directory Paths 12 Names 13 Wildcards 13 Device Names 14 Chapter 2 / Loading MS-DOS and BASIC 17 Loading MS-DOS 17 Making Backups 17 One Drive System 18 Two Drive System 18 LoadingBASIC 19 Loading BASIC via BASICA 19 Options for Loading BASIC 20 Redirection of Input and Output 23 Chapter 3 / Sample Session 27 Loading BASIC 27 Typing the Program 27 Saving the Program on Disk 28 Loading the Program into Memory 28 Chapter 4 / General Information 33 Editing 33 Sample Editing Session 34 SpecialKeys 36 The Key 38 The Key 39

3 Chapter 5 / Basic Concepts 43 Elements of a Program 43 Data 44 Constants 46 Variables 47 Declaring Numeric Constants and Variables 47 Numeric Constants 48 Numeric Variables 48 Numeric Precision Conversion 49 Manipulating Data 51 Arithmetic Operators 51 String Operator 52 Relational Operators 52 Logical Operators 54 Hierarchy of Operators 55 Functions 56 Chapter 6 / Arrays 59 Types of Arrays 62 Defining Arrays 63 Chapter 7 / Disk Files 67 Sequential Access Files 67 Creating a Sequential Access File 68 Updating a Sequential Access File 69 Direct Access Files 70 Creating a Direct Access File 71 Accessing a Direct Access File 73 Chapter 8 / Displaying Color and Graphics 77 Resolution 77 78 VideoPages 79 Selecting Screen Modes 80 Specifying Coordinates 82 Chapter 9 / Introduction to BASIC Keywords 85 Format for Chapter 10 85 Terms Used in Chapter 10 86 Statements 87 Functions 92 Chapter 10 / BASIC Keywords 97

4 Chapter 11 / Technical Information 351 Interfacing With Assembly-Language Routines 351 Memory Allocation Outside BASIC’s Work Area 351 Memory Allocation Inside BASIC’s Work Area 351 CALL Statement 353 CALLS Statement 355 USR Function 355 How Variables are Stored 357 Accessing String Variables 358 File Control Block 358 User Installed Devices 361 Information for Creating Child Processes 361 Chapter 12 / BASIC Error Codes and Messages 365 Appendix A / BASIC Reserved Words and Derived Functions 375 Appendix B / Keyboard and Character Code Charts 379 Keyboard ASCII/Scan Codes 379 ASCII Character Codes 383 Appendix C I Video Display Worksheet 389 Appendix D / Extended Codes 391 Index 393

5

INTRODUCTION TO BASIC

About This Manual This manual describes BASIC for MS-DOS. It is a reference manual, not a tutorial. We assume you already know BASIC and are using this manual to locate information quickly. If you do not know BASIC, see your Radio Shack dealer for the following book: Learning BASZC for the Tandy 200011 000 by David Lien, Cat. No. 25-1500 Your local bookstore has many books about BASIC available that are written in tutorial fashion.

Notations The following notations are used throughout this manual: CAPITALS Material that you must enter exactly as it appears. italics Words, letters, characters, or values within command lines you must supply from a set of acceptable entries. Elsewhere, italics are used for emphasis. . . . (ellipsis) Items preceding the ellipsis may be repeated. [I Items enclosed in brackets are optional. &Hnnnn nnnn is a hexadecimal number. &Onnnnn nnnnn is an octal number. [keynameJ A key on your keyboard. 16 A blank character (ASCII code 32). For exam- ple, in BASICMMPROG two spaces are between BASIC and PROG.

7 Introduction to BASIC

Terms The following terms are used in this manual: buffer An area in memory that BASIC uses to create and access a disk file. A buffer is represented by a number in the range 1 to 15. Once you use a buffer to create a file, you cannot use it to create or access any other files; you must first close the file. You may only access an open file with the buffer used to open it. parameters Information you supply to specify how a com- mand is to operate. arguments Expressions you supply for a function to evaluate. syntax A command with its parameterb), or a func- tion with its argument(s). This shows the for- mat to use for entering a keyword in a program line.

8

Chapter 1 ABOUT BASIC FOR MS-DOS

BASIC for MS”’-DOS is an . This means that, when you run a program, BASIC looks at one statement at a time and executes it before going to the next statement. BASIC also lets you take advantage of many MS-DOS features, such as:

0 Multilevel directories Faster running programs 0 Expanded graphics capabilities

Disk Files BASIC uses the MS-DOS multilevel directory structure on disk. A formatted disk has a main directory called the “root” direc- tory which is represented by the backslash (\). The root direc- tory can contain both files and “second-level’’directories.

This illustration demonstrates how a typical system for a sales and service company might be set up. The root directory con- tains two second-level directories: SALES and SERVICE. The root directory also contains a file called letters.

11 Chapter 1 I About BASIC for MS-DOS

Pathnames BASIC lets you specify pathnames to access disk files just as MS- DOS does. A pathname is enclosed in quotation marks and may be a maximum of 63 characters. It contains the following information:

“[d:I[pathlfilename[.extl”

The drive is specified by d: and may be either A, B, C, or D. If you omit d:,BASIC uses the current drive. Path gives the directory path for filename. The directory names are separated by a backslash ( \ 1. If you omit path, BASIC uses the current directory. Filename specifies the name of the file being accessed. Filenames are 1 to 8 characters long. If a filename is more than 8 character, BASIC truncates it to 8 characters. Ext is an optional extension to the filename. Use extensions to help distinguish types of files. Extensions are always preceded by a pe- riod (.I and are l to 3 characters long. If you omit the extension, BASIC assumes .bas. Here are some common extensions: .bas for BASIC programs .txt for ASCII text .dat for Data files .obj for Object code .re1 for Relocatable code .src for Source code

Directory Paths Some commands, such as CHDIR, MKDIR and RMDIR use a direc- tory path (dirpath) instead of a pathname. The only difference be- tween the two is that a dirpath does not include a filename:

“[d:]path”

The drive identifier (d:)andpath are described above.

12 Chapter 1 I About BASIC for MS-DOS

Names Directory names and filenames must conform to MS-DOS con- ventions. They may contain any of the following characters:

0 uppercase letters (A-Z) 0 lowercase letters (a4 0 decimal digits (0-9) In addition, they may contain the following special characters: $ & # 5% ()- (6 {}-' !'*- An entire pathname (or directory path) may contain a maximum of 63 characters. Some sample filenames are: prog.bas report telephon.sls Some sample directory names are: MEMOS LETTERS EMPLOYEE In this manual, directory names are in uppercase letters, and filenames are in lowercase letters. This lets you easily distin- guish a directory name from a filename.

Wildcards BASIC follows MS-DOS usage of wildcard notations when search- ing for directories or filenames. The wildcard notations are: ? indicates that any character can occupy that position. * indicates that any character can occupy that position or the remaining positions in the filename or extension. For example, if you specify this filename: data?tst.txt BASIC might find these files: dataltst.txt data3tst.txt If you specify this filename: data*.txt

13 Chapter 1 I About BASIC for MS-DOS

BASIC finds those files and might also find these: data.txt datatst.txt datal.txt

Device Names BASIC uses device identifiers (dev:) to indicate a physical device to be used for communication. These names, which must be enclosed in quotation marks, are: KYBD: keyboard. Use for input only. SCRN: screen. Use for output only. LPT1: printer. Use for output only. COMn: RS232 communications channel 1 or 2. Use for input or output. You can open any of these devices just as you would a disk file.

14

Chapter 2 LOADING MS-DOS AND BASIC

The diskette that came with your computer contains MS-DOS and the BASIC Interpreter. Before you begin using BASIC, make backups of this diskette. First, load MS-DOS into the computer.

Loading MS-DOS To start up MS-DOS, turn on your computer and insert the MS- DOSIBASIC diskette into Drive A. See your computer’s introduc- tion book for information on turning on your computer and Drive A. Shortly, MS-DOS prompts you to enter the date and time. We suggest that you enter this information since some BASIC state- ments use the system date and time. MS-DOS displays the proper format. Next, MS-DOS loads and displays its prompt: A> This means that you are at the MS-DOS command level where you can execute a program or command. You should now make backups of your MS-DOSIBASIC diskette.

Making Backups Just as you always keep a spare key for a car, you should keep backup copies of all your diskettes. After you make the backup of your MS-DOSIBASIC diskette, store the original in a cool, dust- free place where it can’t get bent or warped. Also be sure it is not near any magnetic source. If something should happen to any of your backup MS-DOSIBASIC diskettes, be sure to make another backup. Do not use the original diskette except to make backups. You can also use the following procedures to make backups of diskettes you create.

17 Chapter 21 Loading MS-DOS and BASIC

One Drive System 1. At the MS-DOS system prompt (A>), type: FORMAT [ENTER] 2. When prompted, remove the MS-DOSIBASIC diskette and insert an unformatted diskette into Drive A. Press [SPACEBAR] to begin formatting. MS-DOS displays a line of dashes. The dashes change to dots as each track is formatted. 3. When formatting is complete, MS-DOS prompts:

FORMAT another (Y/N)7 Format as many diskettes as you want. When you are through, answer m. 4. Place the MS-DOSIBASIC diskette into Drive A. At the MS- DOS prompt, type: DISKCOPY [ENTER] 5. DISKCOPY prompts you to insert the “target” diskette into Drive A. Remove the MS-DOSIBASIC diskette from Drive A and insert the newly formatted diskette. Press (SPACEBAR] to be- gin copying. Shortly, you are prompted to insert the “so~rce’~ diskette. The source diskette is the MS-DOSIBASIC diskette. MS-DOS will prompt you to swap the diskettes several times. 6. When DISKCOPY is complete, it prompts:

Copy complete. Copy another (Y/N)7 Make a few more backups. When through, type (iJ.

Two Drive System 1. At the MS-DOS system prompt (A>), type: FORMAT E: [ENTER] 2. When prompted, insert an unformatted diskette into Drive B. Press [SPACEBAR] to begin formatting. MS-DOS displays a line of dashes. The dashes change to dots as each track is formatted. 3. When formatting is complete, MS-DOS prompts: FORMAT another (Y/N)?

18 Chapter 21 Loading MS-DOS and BASIC!

Format as many diskettes as you want. When you are through, answer m. 4. At the MS-DOS prompt, type: DISKCOPY A: E: [ENTER) 5. DISKCOPY prompts you to insert the “source” diskette into Drive A and the “target” diskette into Drive B. Insert the newly formatted diskette into Drive B. Since the MS-DOS/ BASIC diskette is already in Drive A, press I. 6. When DISKCOPY is complete, it prompts:

Copy complete. Copy another (Y/N)7 Make a few more backups. When through, type (iJ.

Loading BASIC To load BASIC, first start up MS-DOS as described earlier. When MS-DOS displays its system prompt, A>, you load BASIC by typing 1 of 2 commands. BASIC [ENTER) immediately loads BASIC into the computer’s memory. BASICA [ENTER] loads the small loader program BASICA.COM, which in turn loads BASIC. This alternate method of loading BASIC is dis- cussed in detail in the section “Loading BASIC via BASICA.” Once you load BASIC, a paragraph of copyright information ap- pears on your screen, followed by BASIC’s prompt: Ok. At this point, you can begin using BASIC. The next chapter pro- vides a sample session on loading BASIC and using some of its capabilities. If you don’t want to use any of BASIC’s other op- tions for loading, go ahead to the next chapter.

Loading BASIC via BASICA

Some computers require you to type BAS ICA [ENTER) to load BASIC. To increase compatibility with such computers, your computer also accepts the BASICA command. When you enter the command, the computer executes the program BASICA.COM, which in turn loads BASIC.

19 Chapter 21 Loading MS-DOS and BASIC

In addition to compatibility, other advantages of loading BASIC via BASICA are as follows: If your computer has more than 128K bytes of memory, BASIC is loaded at a different memory location than it would be oth- erwise. This feature lets you run a few BASIC programs that make use of certain memory locations that BASIC would oth- erwise have occupied. You can gain space on your program or system diskette be- cause you can store the BASIC.EXE file on a separate disk. The only limitations imposed by BASICA are: The /I option switch (discussed below) is always on. The communications buffer size is limited to 40K bytes if the system has 1 RS232 card or 20K bytes if it has 2 cards. After you type BASICA[ENTER), BASICA.COM searches the cur- rent directory for the file BASIC.EXE. If it finds BASIC.EXE, BASICA.COM loads it and passes control to it. If BASICA.COM does not find BASIC.EXE, it asks you to replace your program disk with a disk that contains the file. Place a disk containing BASIC.EXE in any drive, and press m.The program searches all drives, beginning with the current drive, until it finds BASIC.EXE or until you press [CTRL][TI. After finding BASIC.EXE, the program asks you to re-insert your program disk if you removed it. Put the disk back in the drive, and press m.The program transfers control to BASIC. Options for Loading BASIC When you load BASIC, you can also specify a set of options, which includes: BASIC [pathnamel[[>loutput-fiZel [IF:# of files1 [/M:highest memory locatwn,maximum block sizel[/C:buffer size] [/S:record lengthl[/Dl[/Il

If you load BASIC by typing BAS I CA [ENTER], the /I switch is al- ways invoked. Other than that, you have the same options, re- gardless of how you load BASIC. Pathname specifies a program to run immediately after BASIC is started.

20 Chapter 21 Loadim MS-DOS and BASIC

[>lOutput-file redirects BASIC’s output to output-file instead of the standard output (video display). If you specify 1 greater- than sign, output file is overwritten. If you use 2 greater-than signs, it is appended. This option must follow input file (if given) and precede all other options in the command line. Redirection of input and output is discussed later in this chapter. IF: specifies the maximum number of data files that may be open at any one time. If you specify the IF: option, you must also specify the /I option. If you omit this option, the number of files defaults to three. The number of open files that MS-DOS sup- ports depends on the value given for the FILES= command in the CONFIG.SYS file. We recommend that you set FILES = 10 for BASIC. BASIC automatically reserves 4 files for internal use. This leaves 6 for BASIC file IIO; thus lF:6 is the maximum sup- ported by MS-DOS when FILES= command is set to 10 in the CONFIGSYS file. Each file you specify may use a maximum 190 bytes of memory. Sequential access files always use 190 bytes of memory. The amount of memory a direct access file uses depends on the record size set with the IS: option. Each direct access file uses 62 bytes of memory for the file control block, plus the record size. For example, if you specify a record size of 50 with the IS: switch, the file uses 112 bytes. 1s: specifies the maximum record size for direct access files. If you use the IS: option, you also must specify the /I option. If you omit the is: option, BASIC assumes 128 bytes. IC: specifies the size of the receive buffer for each RS232 commu- nications channel present in the system. The maximum amount you can specify depends on the number of RS232 cards present in the system and on the method used to load BASIC.

21 Chapter 21 Loading MS-DOS and BASIC

Number Loading Method of Ports Buffer Size BASIC 1 64K bytes BASIC 2 32K bytes BASICA 1 40K bytes BASICA 2 20K bytes

22 Chapter 21 Loading MS-DOS and BASIC

Examples BASIC DEBITS initializes BASIC to 3 data files with all memory available. BASIC then loads and runs the program DEBITS. BASIC PAYROLL /F:5 initializes BASIC to 5 data files with all memory available. BASIC then loads and runs the program PAYROLL. BASIC /M:21000 initializes BASIC to 3 data files and sets the highest memory lo- cation to be used by BASIC at 21000, the first 21000 bytes of BASIC’s data segment. BASIC BUDGET /D initializes BASIC to 3 data files with all memory available. BASIC loads and uses the Double Precision Transcendental math package.

Redirection of Input and Output BASIC lets you redirect input and output. The syntax to redirec- tion is: BASIC [pathname][[>loutput-file1 You can redirect standard input, normally from the keyboard, to the file input-file. Standard output, normally to the video display, can be redi- rected to the file output-file. If output-file already exists, it is ov- erwritten. You can, however, append the output-file to the existing file by using the append notation: >>output-file. If out- put-file does not exist, it is created. The following BASIC statements use standard input: INPUT LINE INPUT INPUT$ INKEY$ The BASIC statements PRINT and WRITE access standard output. Error messages are sent both to the standard output and to the redirected output.

23 Chapter 21 Loading MS-DOS and BASIC

Examples BASIC DAILY >DAILY.OUT initializes BASIC and runs the program DAILY. Redirects all output, normally sent to the screen, to the file DAILY.OUT. BASIC DAILY TSTDATA.OUT initializes BASIC and executes the program SAMPLE. SAMPLE receives input from TSTDATA.IN and sends output to TSTDATA.OUT. BASIC PAYROLL >YTDTOTAL initializes BASIC and executes the program PAYROLL. PAY- ROLL receives input from the file WEEK25. The output is ap- pended to the file YTDTOTAL. Hints for redirection of input and output:

0 File input from the KYBD: device still reads from the keyboard.

0 File output to the SCRN: device still outputs to the screen.

0 BASIC still traps keys when you use the ON KEY0 statement . [CsRLjm] tells BASIC to close all open files, then issue the message “Break in line xxxx” to standard output. Control re- turns to MS-DOS.

0 Redirected input continues until BASIC receives a [CTRLJ[T]. This condition can be tested by the EOFO function. If the in- put file is not terminated by a [CTRL][T]or a BASIC file input statement tries to read past the end-of-file, BASIC closes any open files and issues the message “Read past end” to standard output. Control returns to MS-DOS. e The printer echo key combination ([CTRL][PRlNT)), which nor- mally causes all output on the display to be echoed on LPTl:, will not work if you redirect standard output.

24

Chapter 3 SAMPLE SESSION

The easiest way to learn how BASIC operates is to write and run a program. This chapter provides sample statements and instruc- tions to help familiarize you with the way BASIC works. The main steps in running a program are: 1. Loading BASIC 2. Typing the program 3. Running the program 4. Saving the program 5. Loading the program into memory

Loading BASIC For this sample, load BASIC by typing: BASIC [ENTER)

Typing the Program Type in the sample program below. After typing each line, check it for any mistakes. If there are no mistakes, press I.If you make a mistake, use the [tl key to move the cursor to the mis- take and retype the rest of the line to correct the mistake.

10 A$=”WILLIAM SHAKESPEARE WROTE 15 B$=”THE MERCHANT OF VENICE” [*F 20 PRINT A$; B$ [ENTERJ Check your program again. If you find a mistake, enter the and type the line again. The newly typed line replaces the old line. It does not matter if you enter Line 15 after Line 20; BASIC still reads and executes Line 15 before “looking” at Line 20. BASIC always reads program lines in numerical order. Tell BASIC to execute this program by typing: RUN [ENTER] Your screen should display: WILLIAM SHAKESPEARE WROTE THE MERCHANT OF VENICE

27 Chapter 31 Sample Session

BASIC has powerful special keys that let you correct mistakes without retyping the entire line. These commands are discussed in Chapter 4, "General Information."

Saving the Program on Disk You can save any BASIC program on disk by assigning it a path- name. The pathname tells BASIC on which disk and directory you want to save the file and the name of the file. The pathname must be enclosed in quotation marks. Pathnames must conform to the conventions discussed in Chapter 1, "About BASIC for MS-DOS." For example, to save the program we just wrote on Drive B, in the directory BOOKS with the filename author.bas, use the fol- lowing command: SAVE "E: \BDOKS\author. bas" [ENTER] Notice that BOOKS is located in the root directory since it is preceded by the root symbol ( \ ). You can also save the file with this command: SCIVE "author .wil" which saves the program as author.wi1 in the current directory on the MS-DOS current drive. It takes a few seconds for the computer to find a place on the disk to store a program and to copy the program from memory to the disk. When the program is saved on the disk, BASIC dis- plays its prompt (Ok).

Loading the Program Into Memory If, after writing or running other programs, you want to use this program again, you must load it back into memory from disk. For example, to load the program author.bas from the directory BOOKS, type: LOAD "B:\BOOKS\author .ba5",R

28 Chapter 31 Sample Session

The R option tells BASIC to run the program after loading it. LOAD "author.wi1" loads the file author.wi1 from the current directory on the cur- rent drive. Another way to load and run a program is to type: RUN "pathname" RUN automatically loads and runs the program specified by pathname. The SAVE, LOAD, and RUN commands are discussed in more detail in Chapter 10.

29

ChaDter 4 GENERAL INFORMATION

When BASIC displays the Ok prompt, you can type in program lines or commands. If you want BASIC to read what you type in, you must press [ENTER] at the end of the line. A single line can be a maximum of 255 visible characters. Visi- ble characters are those that take up a space on the display. Since 255 characters cannot fit on one line of the display, BASIC moves the extra characters to the next line. This is called wrap- around. BASIC looks at the first character of a line. If it is a digit, BASIC stores the line in memory as a program line. For exam- ple, if you type:

10 PRINT "THE TINE IS " TIME$ (ENTER] BASIC takes this as a program line and stores it in memory. It does not execute the line until you type RUN and press m. If the first character is not a digit, BASIC tries to execute the line as a command. For example, if you type: MILES=133:GALLON=11:MPG=MILES/G~LLON BASIC immediately executes this line as a command. After it is executed, the statement no longer exists in memory, but the val- ues of the variables MILES, GALLON, and MPG are stored in memory. This BASIC capability lets you use the computer as a calculator for quick computations that do not require an entire program.

Editing BASIC lets you correct errors in program and command lines quickly and efficiently without retyping entire lines. You can use the special keys defined at the end of this chapter to make corrections or changes at any time. To correct a line, sim- ply use the arrow keys to position the cursor on the line you want to alter. After you make changes to the line, press (ENTER) to store the changes.

33 Chapter 41 General Information

When modifying program lines, you can edit specific lines by typing: EDIT line number [ENTER] If the line number you specify does not exist, BASIC returns an "Undefined line number" error. You can also specify the current program line by using a period (.I instead of a line number: EDIT . [ENTER) The current line is the last line entered, the last line altered, or a line in which an error has occurred. Notice that you must type a space before the period; otherwise, BASIC displays a "Syntax error" message. BASIC automatically enters EDIT when a syntax error occurs when executing a program. It displays the line that contains the error and waits for you to make corrections.

Sample Editing Session This sample session shows how you can easily edit lines in BASIC. Even though the sample is a BASIC program, you can use the same procedure for command lines. All special keys used in this session are described at the end of this chapter. Tom: begin the sample session, type the following line and press

100 PRINT "This 15 our example line." Now use the m to position the cursor on Line 100. Use the to move across the line to the T in This. Type lower- case and then [ENTERJ. Remember, none of the changes you make to a program line are recorded until you press m. Type LIST 100 and press [ENTERJ to see that BASIC has stored your change in memory. BASIC displays:

100 PRINT "this 15 our example line." Notice that you can make simple changes by typing over the old material.

34 Chapter 41 General Information

Now, position the cursor over Line 100 again. Press (ENDJ and then use to position the cursor on the second set of quotation marks. Press [M]and type: We inserted the second 5entence. [ENTER] Use the LIST command again to see the new statement that is stored in memory. Now use the EDIT command to edit Line 100. Type: EDIT . [ENTER] Remember, the period (.) tells BASIC to edit the current line. Don’t forget to type a space before the period. Using and W, position the cursor on the i in inserted. Hold down [CTRL) and press [ENDI. BASIC deletes all the characters YOU have inserted except We and the blank space. Press [BACKSPACE) to delete the space. Hold down [CTRL) and press to position the cursor on the pre- ceding word. Press [DELETE) twice to delete We. Press and then FJ to put the quotation mark at the end of the statement. Press [ENTtRl to record the changes. You can use the LIST com- mand to see the new line. Use the EDIT command again, this time with the line number. Type: EDIT 100 (ENTER) Using m, position the cursor on the P in PRINT. Press (SPACEBAR] to change the P to a blank. Press (CTRL] while pressing to position the cursor on the t in this. Press to change the lowercase t to a capital T. Instead of pressing [ENTER] after you make the changes, press @. Use the LIST command. Notice that BASIC did not record your changes because you pressed JESC) instead of m.The IESCJ key tells BASIC to erase the line and not to make any changes to the line. Now you have used most of the special keys in the editor. If you still do not feel comfortable with them, go through the sample session again.

35 Chapter 41 General Information

If you feel confident that you understand the editor, read on to learn about some special keys that make it easier and faster to change lines anywhere on the screen.

Special Keys The following keys perform special functions in BASIC for enter- ing and editing lines. To use some of these keys you must press and hold down the [CTRLJ key while pressing the second key. For example, when you use [CTRL][T]to backspace, hold down the key and press iTJ at the same time. Key Description [CAPS] switches to all uppercase or uppercase1 lowercase mode. (SPACEBAR] changes the current character to a blank and advances the cursor 1 position to the right. backspaces the cursor, erasing the first character to the left. All characters to the right move left 1 position. Use this to correctm. typing errors before you press interrupts line entry and starts over with a new line. Any changes previously made to the line are not saved. ends the current line. BASIC reads the line. [ESCI or [TK][T] erases the entire line from the screen, but not from memory. clears the screen and positions the cursor at the first position in Row 1. clears the screen from the current cursor position to the end of the screen. [DELETE] deletes the character at the cursor posi- tion and moves all remaining characters to the left 1 position.

36 Chapter 41 General Information

[INSERT] or (CTRL][T] turns the insert mode on if it is off; or off if it is on. The insert mode lets you add new characters to the line at the cursor position. (HOME] or [CTRL][F] moves the cursor to the first position in Row 1. moves the cursor to the end of the line. deletes all characters from the current cursor position to the end of the line. [TAB] or [CTRL][T] advances the cursor to the next tab posi- tion. Tab positions are set at every 8 characters . @ or [CTRL][T] moves the cursor 1 position to the left. moves the cursor 1 position to the right.

or [CTRLJIT] moves the cursor up 1 row to the charac- ter above the current cursor position. or moves the cursor down 1 row to the char- [CTRLJ[:] acter below the current cursor position.

moves the cursor to its left and to the first character in the preceding word, which is the first character preceded by a blank. moves the cursor to its right and to the first character in the next word, which is the first character preceded by a blank. rings the bell at the terminal. issues a linefeed. This moves the cursor to the next line of the display without ex- ecuting or storing the line.

37 Chapter 41 General Information

The following special keys act differently while BASIC is execut- ing programs or commands: IHOLD] pauses execution. Press [HOLD] again to continue. [rnJrnJ terminates execution and returns you to BASIC’s prompt. IENTER] or [CTRL][T] signifies the end of data entry. When a BASIC program or command prompts you to enter data, press [ENTERI to end the response.

The (ALT] Key The [ALTI key provides a quick and easy way to type certain BASIC keywords. These keywords are associated with alphabetic characters (A-Z). To enter these keywords, press and hold down the [ALTJ key while pressing the desired letter. BASIC inserts the keyword at the current cursor position. The keywords and their associated let- ters are listed below. A AUTO N NEXT B BSAVE 0 OPEN C COLOR P PRINT D DELETE Q (none) E ELSE R RUN F FOR S SCREEN G GOT0 T THEN H HEX$ U USING I INPUT V VAL J (none) W WIDTH K KEY X XOR L LOCATE Y (none) M MOTOR* Z (none) *MOTOR is a reserved word, but is not recognized in this imple- mentation of BASIC.

38 Chapter 41 General Information

The Kev Pressing [sHlFT][PRlNT] dumps the current text content of the screen to the line printer LPT1:. [CTRL][PRlNTJis the line printer echo key, which acts as a toggle switch. If the echo is off, pressing [CTRL][m]once causes all characters sent to the screen to also be sent to the line printer LPT1:. Pressing [CTRL][m] a second time turns off this echo feature.

39

Chapter 5 BASIC CONCEPTS

This chapter describes the different ways BASIC handles and manipulates data. By understanding how BASIC does this, you can build more efficient programs.

Elements of a Program A program is a group of instructions that performs a certain task. It is made up of 1 or more numbered lines. Each line can contain a maximum of 255 visible characters. Of the 255 characters, BASIC automatically reserves 1 space for each digit in the line number and another space for the space fol- lowing the line number. If you enter more than 255 visible char- acters, BASIC truncates the line. Here is a sample program line: 10 PRINT "one" A line number is always the first element of a program line. In BASIC line numbers must be in the range 0 to 65529. In the sample program line, the line number is 10. A BASIC statement follows the line number. A statement tells BASIC to perform a specific operation. In the sample program line, the statement is PRZNT "om". This statement tells BASIC to print, or display, the word om on the screen. You can have more than 1 statement on a program line by plac- ing a colon between each statement. For example:

20 FOR X = 1 TO 5:PRINT "one":NEXT X This program line has 3 statements. They are:

1. FORX = 1TO5 2. PRINT "one" 3. NEXTX You can add explanations, or remarks, to your program lines. A remark is preceded by a single quotation mark to separate it from the statements. Here is a program line with a remark:

20 FOR X = 1 TO 5:PRINT "one":NEXT X 'loop

43 Chapter 51 Basic Concepts

Data Data is information on which BASIC performs its operations. Data can be numbers, characters, or symbols. BASIC classifies data into two groups: string and numeric. String data is a sequence of ASCII characters, graphics or non- ASCII symbols. A string can be a maximum of 255 characters. If the string is entered on a program or command line, it must be enclosed in quotation marks (see “Constants” later in this section). If the string is entered in response to a prompt, it is not enclosed in quotation marks. BASIC does not evaluate string data; it simply stores it for the program to use or manipulate. Hint: ASCII stands for American Standard Code for Information Interchange. In ASCII, each character has a unique number that represents it. This is necessary since computers understand and process only numbers. Here are some sample strings:

“~1~37 “MAIN STREET” “255 CENTRAL AVE” “25 dollars” “$250” “2 + 4” Notice that numbers can be in a string. Remember, BASIC does not evaluate strings. Type the following line at BASIC’s prompt:

PRINT “2 + 4” BASIC does not add 2 and 4. It obeys the command PRINT and displays 2 + 4 on your screen. Strings use 3 bytes of memory plus the number of characters in the string. For example, the string “CATS” takes up 7 bytes of memory: 4 for the string plus 3. Numeric data consists of positive and negative numbers. BASIC divides numeric data into 5 groups: integer, single precision, double precision, hexadecimal, and octal. Integers are whole numbers in the range -32768 to +32767 that do not contain a decimal point. For example: 1 3200 -2 500 -12345 Integers use the least amount of memory (2 bytes). Because they use less memory, BASIC can access them fastest.

44 Chapter 51 Basic Concepts

Single precision numbers can be a maximum of 7 digits and may have a decimal point. Single precision numbers must be in the range to Sample single precision numbers are: 10.001 -200034 123.4567 If a single precision number is more than 7 digits, BASIC dis- plays the number in scientific notation, or exponential format, in the E form. For example: 1.74E 6.9838 1043-7 BASIC stores a single precision number in 4 bytes of memory. Double precision numbers can include a maximum of 16 digits and may have a decimal point. Double precision numbers have the same range as single precision numbers. Sample double pre- cision numbers are: 1010234567 -8.7777651010 If a double precision number is more than 16 digits, BASIC dis- plays the number in scientific notation, or exponential format, in the D form. For example: 8.00100708D12 -6.7765499824D16 BASIC stores double precision numbers in 8 bytes of memory. Al- though double precision numbers consume more memory, they are the most exact. Hexadecimal numbers are the hexadecimal representation of dec- imal numbers. They contain 1 to 4 digits and are preceded by &H. The hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Here are some hexadecimal numbers and their decimal equivalents: Hex Decimal &H76 118 &H02FF 767 &HFF 255 BASIC stores hexadecimal numbers as integers.

45 Chapter 51 Basic Concepts

Octal numbers are the octal representation of decimal numbers. They contain 1 to 6 digits and are preceded by &O or &. Al- though only the & is required, we recommend that you use &O for clarity in your programs. The octal numbers are 0, 1, 2, 3, 4, 5, 6, and 7. Here are some octal numbers and their decimal equivalents: Octal Decimal &7 7 &0123 83 &0000456 302 BASIC stores octal numbers as integers.

Constants Constants are values input to a program that are not subject to change. Constants can be either string or numeric data (integer, single or double precision, hexadecimal, or octal). Numeric data that will not change can be represented as either a string or numeric constant. If you use punctuation in the num- ber, it must be a string constant. For example:

PR I NT "$25 0 ,00 0 " When BASIC encounters a data constant in a statement, BASIC must determine how to store it: If the value is enclosed in quotation marks, BASIC stores it as a string. If the value is not enclosed in quotation marks, BASIC stores it as an integer or a single precision or a double pre- cision number, according to the requirements described in the previous section. The section, "Declaring Numeric Con- stants and Variables," describes ways to override BASIC's classification of constants. BASIC evaluates numeric constants in program lines as soon as you enter the line. It does not wait until you run the program. If any numbers are out of range for their type, BASIC returns an error message immediately. Here are some examples of constants:

PR I NT -NAME*', "ADDRE s si' , "c I TY91 , "STATE"

46 ChaDter 51 Basic ConceBts

This line contains 4 string constants: NAME, ADDRESS, CITY, and STATE. These values will not change. Every time BASIC ex- ecutes this statement, the same 4 words are printed. PRINT “1 000 PLUS”; 2000; “EQUALS”;3000 The 1000 is a string constant, the 2000 and the 3000 are nu- meric constants.

Variables Variables are symbolic names for a value in a BASIC program. A variable name can be a maximum of 40 characters and must be- gin with a letter (A-Z). Note: You cannot use any of the reserved words listed in Appendix A as variable names. However, reserved words may be imbedded in a variable name. The following are examples of variable names: A A1 ADDRESS ADDRESS. OLD L L2 LEN2 LENGTH The 2 types of variables are string and numeric. BASIC initially classifies all variables as single precision with a value of zero (0). (The next section describes how to declare variables as string, integer, or double precision variables.) The following examples assign a value to a variable.

LET A = 12345 A = 601 .432 BALANCE = 338.92 BASIC automatically stores all the above examples as single pre- cision numbers. Chapter 10, “BASIC Keywords,” describes more ways to assign values to variables.

Declaring Numeric Constants and Variables BASIC lets you override its automatic classification of numeric constants and variables.

47 Chapter 51 Basic Concepts

Numeric Constants To change the way BASIC stores a numeric constant, add one of the following symbols to the end of the number. If BASIC must shorten a number to meet the new requirements, it rounds the number. ! declares a single precision number. For example, BASIC stores the number 12.345678901234! as a single precision - number: 12.34568. E declares the number a single precision exponential number. For example, BASIC stores the number 1.2E5 as a single precision number: 120000. # declares a double precision number. For example, BASIC stores the number 1.5# as a double precision number: 1.5. BASIC does not expand constants when declaring them dou- ble precision. D declares the number a double precision exponential number. For example, BASIC stores the number 1.2D2 as a double precision number: 120. See the next section on converting numbers for important infor- mation on converting from numbers to another precision.

Numeric Variables BASIC initially classifies all numeric variables as single preci- sion. You can declare variables as other than single precision in 2 ways: Append a symbol to the variable name: % declares an integer variable. BASIC stores the value of the variable as an integer. I%, FT%, and COUNTER% are samples of integer-declared variables. ! declares a single precision variable. BASIC stores the value of the variable as a single precision number. F!, NM!, and BALANCE! are samples of variables declared as single precision.

48 Chapter 51 Basic Concepts

# declares a double precision variable. BASIC stores the value of the variable as a double precision number. S#, AD#, and YTDTOTAL# are samples of variables de- clared as double precision. $ declares a string variable. The value of the variable must be enclosed in double quotes. A$, WRD$, and CITY$ are samples of variables declared as string variables. Note: Any variable name can represent 4 different variables. For example, A5%, A5!, AS#, and A5$ are all valid and distinct variable names.

0 Use the following BASIC statements: DEFINT Defines specified variableh) as integer. DEFSNG Defines specified variable(s) as single precision. (Since BASIC initially classifies all variables as single precision, you need to use DEFSNG only if one of the other DEF statements is used.) DEFDBL Defines specified variableb) as double precision. DEFSTR Defines specified variableb) as string. Chapter 10 describes these BASIC statements fully.

Numeric Precision Conversion Your program may ask BASIC to convert numeric data from one precision to another. The following section describes this procedure. When converting singleldouble precision to integers, BASIC rounds the fractional portion of the number, if any. For example:

A% = 32766.7 BASIC stores as 32767 A% = -123.4567 BASIC stores as -123 When converting integers to singleldouble precision, BASIC ap- pends a decimal point and zeroes to the right of the original value. For example:

A# = 32767 BASIC stores as 32767.00000000000 A! = -1234 BASIC stores as -1234.000

49 Chapter 51 Basic Concepts

When converting double to single precision, BASIC rounds the number to 7 significant digits. For example:

A! = 1.2345678901234567 BASIC stores as 1.234568 A! = 1.3333333333333333 BASIC stores as 1.333333 When converting single to double precision, BASIC adds trailing zeroes to the right of the original value. If the original value has an exact binary representation in single precision format, the re- sulting value is accurate. For example:

A# = 1.5 BASIC stores as 1.50000000000000 However, if a number does not have an exact binary representa- tion, the conversion creates an erroneous value. For example:

A# = 1.3 BASIC stores as 1.299999952316284 You should not use such conversions in your program because most fractional numbers do not have exact binary representa- tions. You can avoid this by forcing the constant to be double pre- cision, such as:

A# = 1.3# or A# = 1.3D which BASIC stores as 1.3. If you must convert from single to double precision, the following programs show a special technique. Type and run the following program:

10 A! = 1.3 20 A# = A! 30 PRINT A# BASIC prints 1.299999952316284 Now type and run this program:

10 A! = 1.3 20 A# = VAL(STRS(A!)) 30 PRINT A# BASIC prints 1.3. Converting the single precision number to a string before converting it to a double precision value causes BASIC to store the value accurately. Note: BASIC cannot automatically convert numeric data to string data or vice versa. This results in a “Type mismatch” error. Use the VAL and STR$ func- tions to accomplish this kind of conversion.

50 Chapter 51 Basic Concepts

Manipulating Data BASIC uses expressions as a way to manipulate data. An expres- sion is 2 or more pieces of data connected by operators. An operator is a symbol or a word that signifies some action to be performed on the specified data. Each data item is called an operand. An expression might look like this: operand1 operator operand2 6 + 2 A few operators allow only one operand, for example operator operand - 5 Expressions must be used in a BASIC statement, such as: A=6+2 PRINT -5 BASIC has four types of operators: Arithmetic used for numeric data only. String used for string data only. Relational used for both numeric and string data. Logical used for numeric data only.

Arithmetic Operators Arithmetic operators perform operations on numeric data. Both operands must be numeric. When BASIC evaluates the expres- sion, all operands are converted to the same degree of precision, that of the most precise operand. The result of the arithmetic op- eration is also returned to this degree of precision. The arithmetic operators are listed below. They are in order of precedence, that is, the order in which BASIC executes them if 1 or more operators are in the same statement. A Exponentiation. Calculates the power of a number. For example, 2^3 is 8 (2 to the power of 3 is the same as 2*2*2). Negation or Unary Minus. Makes a number negative. For example, -10 is “negative ten.”

51 Chapter 51 Basic Concepts

*, I Multiplication, Division. For example, 3*3 is 9, and 1015 is 2. \ Integer Division. BASIC rounds both operands to integers and truncates the result to an in- teger. Integer division is faster than standard division. For example, 10\4 is 2. MOD Modulus Arithmetic. BASIC performs integer division as described above and returns the remainder as an integer value. For example, 10 MOD 3 results in 1.

+, - Addition, Subtraction. For example, 2+9 is 11, and 15-8 is 7.

String Operator The string operator is the plus sign ( + 1. It appends one string to another. All operands must be strings, and the resulting value is 1 string. For example:

PRINT "APRIL SHOWERS 'I + "BRING" + '' MAY FLOWERS. " prints APRIL SHOWERS BRING MAY FLOWERS.

Relational Operators Relational operators compare 2 pieces of numeric data or 2 pieces of string data. The result of the comparison is either true or false. If the relationship is true, BASIC returns -1. If the rela- tionship is false, BASIC returns 0 (zero). The relational operators are, in order of precedence: - Equal. Both operands are equal. < Less Than. The first operand is less than or precedes the second operand. > Greater Than. The first operand is greater than or follows the second operand. >< or <> Inequality. The operands are not equal.

52 Chawter 51 Basic ConceDts

<= or =< Less Than or Equal To. The first oper- and is less than (precedes) or is equal to the second operand. >= or => Greater Than or Equal To. The first operand is greater than (follows) or is equal to the second operand. Relational operators are usually used within an IFiTHEN state- ment. For example:

IF CI = 1 THEN PRINT "CORRECT" BASIC looks at the value in variable A. If the value is equal to 1, BASIC prints the word CORRECT. If arithmetic and relational operators are combined in the same expression, BASIC evaluates the arithmetic operations first. For example :

IF X*Y/2 <= 15 PRINT "4VERAGE SCORE" BASIC performs the arithmetic operation X*Y/2 and then com- pares the result with 15. When relational operators are used with strings, BASIC compares the strings character by character. When it finds 2 characters that do not match, it checks to see which character has the lower value ASCII code. The character with the lower ASCII code comes before the word with the higher ASCII value in an alphabetical listing, just as one word comes before another in a dictionary. Consider these examples: "fl" < llgll

BASIC compares the ASCII value of the 2 strings. The ASCII value for A is 65, and the ASCII value for B is 66. Since 65 is less than 66, BASIC returns a -1. BASIC displays the result if you type PRINT and the expression. For example, PRINT "A">"B". "CODE" > "C 00 L" This is false. The first 2 characters of the strings match. How- ever, the third character does not. BASIC then compares the AS- CII codes. The ASCII code for D is 68 and the code for 0 is 79. Since 79 is not less than 68, BASIC returns a 0. "TRAIL" < "TRA I LER"

53 Chapter 51 Basic Concepts

This is true. If BASIC reaches the end of one string before find- ing 2 characters that don’t match, the shorter string is consid- ered the less of the two strings (lower in precedence). Therefore, TRAIL is the lesser of the two strings. Also note that leading blanks are significant in string compari- sons. Therefore, ‘‘ A” comes before “A” because the ASCII code for blank is 32 and the ASCII code for A is 65.

Logical Operators Logical operators, or Boolean operators, make logical compari- sons of numeric values. The logical operators are NOT, AND, OR, XOR, EQV, and IMP. They take a set of truelfalse values, usually from relational expressions, and return a true or false result. The following table describes the result for each logical operator given the described truelfalse values. Meaning of First Second Operator Operation Operand Operand Result NOT The result is the oppo- 1 0 site of the operand. Q 1 AND When both values are 1 1 true, the result is 1 0 true. Otherwise, the 0 Q result is false. 0 0 OR When both values 1 1 are false, the 1 1 result is false. 0 1 Otherwise, the 0 0 result is true. XOR When one of the 1 1 0 values is true, the 1 0 1 result is true. 0 1 1 Otherwise, the 0 0 0 result is false. EQV When both values 1 1 1 are true or both 1 0 0 values are false, 0 1 0 the result is true. 0 0 1 IMP The result is true 1 1 1 unless the first 1 8 0 value is true and 0 1 1 the second value is 0 0 1 false.

54 Chapter 51 Basic Concepts

Normally, logical operators are used in IFiTHEN statements. For ex ample :

IF A = 1 OR C = 2 THEN PRINT X BASIC prints the variable X if 1 or both of the relational expres- sions are true. If both are false, BASIC does not print the vari- able x.

IF S$ = "TEXAS" CIND C$ = "AUSTIN" THEN PRINT Z$ BASIC prints the value of Z$ if S$ contains the word TEXAS and C$ contains the word AUSTIN. You may also use logical operators to make bit comparisons of 2 numeric expressions. In this case, BASIC does a bit-by-bit com- parison of the 2 values, according to predefined rules for the spe- cific operator. Note that the operands are converted to integer type, stored internally as 16-bit, two's complement numbers. This information is important when doing bit comparisons.

Hierarchy of Operators BASIC uses a predefined hierarchy when performing operations on expressions with multiple operators. This list shows the oper- ators in the order that BASIC would perform the operations in a statement. Remember, BASIC evaluates statements from left to right. Operators with the same level of hierarchy are shown on the same line.

A

unary - */ \ MOD +- < > = <= >= <> NOT AND OR, XOR EQV IMP Consider this expression: X * X + 5^2.8

55 Chapter 51 Basic Concepts

BASIC evaluates 5 to the 2.8 power first, then multiplies X*X, and finally adds the 2 values. You can change the order of the hierarchy by adding parentheses to an expression. BASIC always evaluates the expressions inside the parentheses before evaluating the rest of the expression. Look at this expression: X * (X + 5Y2.8 BASIC evaluates the expression (X + 5) first and raises that value to the 2.8 power before performing the multiplication. If an expression contains multiple parentheses, BASIC evaluates the innermost parentheses first. Functions A function is a built-in sequence of operations that BASIC per- forms on data. BASIC always performs functions first when eval- uating a statement. Numeric functions, such as ABS, SQR, and COS, perform prede- fined operations on numeric data. String functions, such as MID$, VAL$, and LEN$, perform oper- ations on string data. Functions are described in Chapter 10.

56

Chapter 6 ARRAYS

An array is a group of related data values stored consecutively in memory. The entire group of data values is referred to by one variable name. Each data value is called an element of the array. A subscript is an integer used to refer to each element of the ar- ray. For example, an array named A may contain 3 elements re- ferred to as: A(1) A(2) A(3)

Note: Normally array elements start with Element 0; however, to simplify this example, it starts with Ele- ment 1. You can modify the initial array element base- number with the OPTION BASE statement. You can use each of these elements to store a separate data value, such as:

A(1) = .10 A(2) = .20 A(3) = .30 You can imagine an array as a row of boxes, with the numbers on them to identify them. Each box can hold a different value. For example, Array A may hold your expenses.

Grocery Gas Clothes Expense Expense Expense

This is a 1-dimensional array, because elements are arranged in a single row and only one subscript is used to an element. For example, A(1) holds your grocery expense.

59 Chapter 61 Arrays

This program creates a 1-dimensional array: 5 :OPTION BASE 1 10 DATA GROCERY,GAS,CLOTHES 20 DIM A(3) 30 FOR C = 1 TO 3 40 READ NAMES$ 50 PRINT "ENTER THE "NAMES$" EXPENSE IN DOLLARS" 60 INPUT A(C) 70 NEXT C The DIM statement in Line 10 reserves space in memory for an array named A with 3 elements. As you enter the expenses, the grocery expense is stored in A(l), the gas expense in A(2) and the clothes expense in A(3). Add these lines to the program to print the contents of Array A: 100 RESTORE 110 FOR C = 1 TO 3 120 READ NAMES$ 130 PR1NT:PRINT NAMES$ " = " A(C) 140 NEXT C Use RUN to see the results of this program. You can add more dimensions to the array such as storing the expenses by weeks.

Col 1 Col 2 Col 3 Grocery Gas Clothes

Row 1 Week 1

Row 2 Week 2 A(3,2) = Row 3 Gas expense Week 3 for Week 3

Row 4 Week 4

60 Chmter 61 Arrays

This is a 2-dimensional array. Each element is referred to by 2 subscripts: A(row,column) For example, A(3,2) points to the third week's gas expense. To make a 2-dimensional array from the earlier program, add the following lines:

25 FOR R = 1 TO 4:RESTORE 75 NEXT R 105 FOR R = 1 TO 4:RESTORE 150 NEXT R and change these lines:

20 DIM A(4,3): W = 1 50 PRINT "ENTER THE ";NAMES$;" EXPENSES IN DOL- LARS FOR WEEK NO: "W 60 INPUT A(R,C) 70 NEXT C: W = W + 1 100 RESTORE: W = 1 130 PR1NT:PRINT NAMES$;" EXPENSE FOR WEEK NO: ";W;" = ";ACR,C) 140 NEXT C:W = W + 1 Run this program and see how it works. We simply added an- other subscript to the original array. Now instead of referring to an element by a row number only, we refer to it by both a row and column number. You can add yet another dimension, or subscript, to the array by adding these lines:

22 FOR P = 1 TO 2: RESTORE 78 W = 1: NEXT P 102 FOR P = 1 TO 2: RESTORE 160 W = 1 :NEXT P and changing these lines:

20 DIM A<2,4,3):W = 1: M = 1 50 PRINT "ENTER THE ";NAMES$;" EXPENSE IN DOL- LARS FOR WEEK NO: ";W;" OF MONTH NO: ";M 60 INPUT A(P,R,C) 75 NEXT R: M = M + 1 100 RESTORE: W = 1: M = 1 130 PR1NT:PRINT NAMES$;" EXPENSE FOR WEEK NO: ";W;" OF MONTH NO: ";M;" = ";ACP,R,C) 150 NEXT R: M = M + 1 Run the program to see how it works.

61 Chapter 61 Arrays

Page 2 Month 2 Page 1 Month 1 Row 1 Week 1

Row 2 Week 2

Row 3 Week 3

Row 4 Week 4 Col 1 Col 2 Col 3 Grocery Gas Clothes

Imagine the third dimension as an entirely new page. Here, you refer to an element in the array by using 3 subscripts: A(page, row, column) For example, in A(1,2,1), the first subscript (1) stands for the month. The second subscript (2) stands for the week and the third subscript (1) stands for the Grocery category. So A(1,2,1) contains the Grocery expense for the second week of the first month.

Types of Arrays Arrays may be of any type: string, integer, single precision, or double precision. You can have a maximum of 255 dimensions in your array and a maximum of 32,767 elements in each dimen- sion. The amount of memory that an array occupies is equal to the number of bytes it takes to store that type of variable times the number of elements. For example, if you have a double precision array of 30 elements, it occupies 240 bytes of memory. Remem- ber, double precision numbers are stored in 8 bytes of memory.

62 Chawter 61 Arravs

Defining Arrays You can define arrays in your BASIC program by placing a DIM statement at the beginning of your program or by setting the value of an element in the program. For example: cIC5) = 300 automatically creates an array named A containing 6 elements and assigns element A(5) the value 388. Use this method only if your array contains fewer than 11 elements (8-10). If your array contains more than 11 elements, you must use the DIM statement. Use a DIM statement to reserve space in memory for each ele- ment of the array. For example: DIM C#(99) creates Array C and reserves memory space for 100 double preci- sion elements. See the DIM statement in Chapter 10 for more information on creating arrays.

63

ChaDter 7 DISK FILES

You may want to store data on disk for future use. To do this, you need to store the data in a file. A file is an organized collec- tion of related data. It may contain a mailing list, a personnel record, or almost any kind of information. You access this information in records. A record is a small por- tion of data from the disk file such as a name and address in a mailing list file. A record is the largest block of information that you can address with a single command. With BASIC you can create and access 2 types of files: sequen- tial access or direct access.

Sequential Access Files With sequential access files, you can access data only in the same order as it was originally stored. To read from or write to a particular section in the file, you must first read through all the records in the file from the beginning until you get to the de- sired record. Data is stored in a sequential access file as ASCII characters. Therefore, it is ideal for storing free-form data without wasting space between data items. However, it is limited in flexibility and speed. The statements and functions used with sequential files are: WRITE # LOC EOF OPEN PRINT# INPUT# LOF CLOSE PRINT USING # LINE INPUT# These statements and functions are discussed in more detail in Chapter 10.

67 Chapter 71 Disk Files

Creating a Sequential Access File 1. To create the file, open it in Output mode (with the letter 0) and assign it a buffer number in the range 1 to 15. For example: OPEN "O", 1, "li5t .dat" OPEN "list. dat" FOR OUTPUT AS 1 Either form of the syntax for the OPEN statement opens a se- quential output file named list.&t and gives Buffer 1 access to this file. 2. To input data from the keyboard into 1 or more program vari- ables, use either INPUT or LINE INPUT. For example: LINE INPUT, "NAME? "; N$ inputs data from the keyboard and stores it in variable N$. 3. To write data to the file, use the WRITE# statement (you also can use PRINT#, but be sure you delimit the data). For example: WRITE# 1, N$ writes variable N$ to the file, using Buffer 1 (the buffer used to open the file). Remember that data must go through a buffer before it can be written to a file. 4. To ensure that all the data has been written to the file, use the CLOSE statement. For example: CLOSE 1 closes access to the file that uses Buffer 1 (the same buffer used to open the file). Sample Program 10 OPEN "O", 1, "115t.dat" 20 LINE INPUT "ENTER A NAME OR 'DONE' TO END > ";N$ 30 IF N$ = "DONE" THEN 60 40 WRITE# 1, N$ 50 PRINT: GOT0 20 60 CLOSE 1

68 Chapter 71 Disk Files

The file list.dat stores the data you input through the aid of the program, not the program itself. To save the program above, you must assign it a name. Use the SAVE command as described in Chapter 3. For example, SAVE "payroll.bas". Every time you modify a program, you must save it again (you can use the same name); otherwise, the original pro- gram remains on disk, without your latest corrections. 5. To access data in the file, reopen it, this time in the Input mode with the letter I. For example: OPEN "115t.dat" FOR INPUT AS 1 opens the file named 1ist.dut for sequential input, using Buffer 1. 6. To read data from the file and assign it to program variables, use either INPUT# or LINE INPUT#. For example: INPUT# 1, N$ reads a string item into N$, using Buffer 1 (the buffer used when the file was opened). LINE INPUT# 1, N$ reads an entire line of data into N$, using Buffer 1. Sample Program 10 OPEN "I", 1, "1ist.dat" 20 IF EOF(11, THEN 100 30 INPUT#l, N$ 40 PRINT N$ 50 GOT0 20 100 CLOSE 1 Updating a Sequential Access File 1. To add data to the file, open it in Append mode with the let- ter A. For example: OPEN "A", 1, "list .dat" opens the file 1ist.dat so that it can be extended. The data you enter is appended to the file 1ist.dat.

69 Chapter 71 Disk Files

2. To enter new data to the file, follow the same procedure as for entering data in the Output mode. The following program illustrates this technique. It builds upon the file previously created. Note: Read through the entire program first. If you encounter BASIC keywords that are unfamiliar to you, refer to Chapter 10 for their definitions. Sample Program

10 OPEN "A", 1, "115t.dat" 20 LINE INPUT "TYPE A NEW NAME OR PRESS "; N$ 30 IF N$ = "N" THEN 60 40 WRITE# 1, N$ 50 GOTO 20 60 CLOSE 1 If you want the program to print on your display the informa- tion stored in the updated file, add the following lines: 70 OPEN "li5t.dat" FOR INPUT AS 1 80 IF EOFCI) THEN 200 90 INPUT# 1, N$ 100 PRINT N$ 110 GOTO 80 200 CLOSE 1 After you have run this program, save it. For example, type SAVE "payroll2.bas" to save the program under a different name than the previous program.

Direct Access Files With a direct access file, you can access data anywhere within the file. It is not necessary to read through all the information, as with a sequential access file, because in a direct access file you can access each record of information individually by its number. More program steps are required to create and access direct ac- cess files, but they are more flexible and easier to update than sequential access files.

70 Chapter 71 Disk Files

BASIC allocates space for records in numeric order. That is, if the first record you write to the file is number 200, BASIC allo- cates space for records 0 through 199 before storing record 200 in the file. The maximum number of logical records is 16,777,215. Each record may contain a minimum of 1 and and a maximum of 32 7 68 bytes. The statements and functions used with direct access files are: OPEN FIELD LSETiRSET CLOSE GET PUT MKD$ MKI$ MKS$ CVD CVI cvs LOC LOF These statements and functions are discussed in more detail in Chapter 10. Creating a Direct Access File 1. To create the file, open it for random access in Random mode (''R'). For example: OPEN "R", 1, "listing.dat", 32 opens the file named listing.dat, gives Buffer 1 direct access to the file, and sets the record length to 32 bytes. (If you omit the record length, the default is 128 bytes.) Remember that data is passed to and from the disk in records. 2. Use the FIELD statement to allocate space in the buffer for the variables that will be written to the file. This is neces- sary because you must place the entire record into the buffer before putting it into the disk file. For example: FIELD 1, 20 AS N$,4 AS A$,8 AS P$ allocates the first 20 positions in Buffer 1 to string variable N$, the next 4 positions to A$, and the next 8 positions to P$. The variables N$, A$, and P$ are now "field names."

71 Chapter 71 Disk Files

3. To move data into the buffer, use the LSET statement. Nu- meric values must be converted to strings when placed in the buffer. To do this, use the make functions: MKI$ to make an integer value into a string, MKS$ for a single precision value, and MKD$ for a double precision value. For example: LSET NS=XS LSET A$=MKSSCAMT) 4. To write data from the buffer to a record (within a direct ac- cess disk file), use the PUT statement. For example: PUT 1, CODE% writes the data from Buffer 1 to a record with the number CODE%. (The percentage sign at the end of a variable speci- fies that it is an integer variable.) The following program writes information to a direct access file: 10 OPEN "R", 1, "li5ting.dat",32 20 FIELD 1, 20 AS NS, 4 AS AS, 8 AS PS 30 INPUT "2-DIGIT CODE, 0 TO END"; CODE% 40 IF CODE% = 0 THEN 130 50 INPUT "NAME"; XS 60 INPUT "AMOUNT"; AMT 70 INPUT "PHONE"; TELS 80 LSET NS = XS 90 LSET AS = MKS$(AMT) 100 LSET PS = TELS 110 PUT 1, CODE% 120 GOT0 30 130 CLOSE 1 The 2-digit code that you enter in Line 30 becomes a record number. That record number stores the name(s1, amount(s1, and phone number(s) you enter when Lines 50, 60, and 70 are executed. The record is written to the file when BASIC exe- cutes the PUT statement in Line 110.

72 Chapter 71 Disk Files

After typing this program, save it and run it. Then, enter the following data: 2-DIGIT CODE, 0 TO END? 20 IENTER]

2-DIGIT CODE, 0 TO END? 0 [ENIER) BASIC stores SMITH, 34.55, and 567-9000 in Record 20 of file 1isting.bas. Accessing a Direct Access File 1. Open the file in Random mode: OPEN "R", 1 ,"listing.dat",32 2. Use the FIELD statement to allocate space in the buffer for the variables that will be read from the file. For example: FIELD 1, 20 AS N$, 4 AS A$, 8 AS P$ 3. Before you use the GET statement to read the record, you can check to see if the record is in your file. Set a variable in your program equal to the record size you used in the OPEN statement. LOF returns the length of the file in bytes. The to- tal number of bytes in the file divided by the record size is equal to the largest record number in the file. An attempt to access a record number greater than the largest record num- ber in the file results in an "Input past end" error. For example: RECSIZE = 32 IF CODE% > (LOF(1) / RECSIZE%) THEN 1000 4. Use the GET statement to read the desired record from a di- rect disk file into a buffer. For example: GET 1, CODE% gets the record numbered CODE% and reads it into Buffer 1.

73 Chapter 71 Disk Files

5. Convert string values back to numbers using the "convert" functions: CVI for integers, CVS for single precision values, and CVD for double precision values. For example: PRINT N$ PRINT CVS(A$) The program may now access the data in the buffer. The following program accesses the direct access file list- ing.dat (created with the previous program). When BASIC ex- ecutes Line 30, enter any valid record number from 1isting.dat.This program prints the contents of that record.

10 OPEN "R", 1, "ll5tlng.dat", 32 20 FIELD 1,20 AS N$,4 AS A$,8 AS P$ 30 RECSIZE% = 32 40 INPUT "2-DIGIT CODE, 0 TO END"; CODE% 50 IF CODE% =0 OR CODE% > (LOF(l)/RECSIZE%) THEN 1000 60 GET #I, CODE% 70 PRINT N$ 80 PRINT USING 'I$$#.##"; CVSCA$) 90 PRINT P$: PRINT 100 GOT0 40 1000 CLOSE 1 After typing this program, save it and run it. When BASIC asks you to enter a 2-digit code, enter 20 (the record created through the previous program). Your display should show: 2-DIGIT CODE, 0 TO END? 20 SM I TH $34.55 567-9000 To update listing.dat, simply use LOAD to load the previous program (the one that created listing.dat) and run it.

74

Chapter 8 DISPLAYING COLOR AND GRAPHICS

Interpreter BASIC includes many commands to display text and graphic images in black and white and in color. You first select a screen mode, which tells BASIC the size of the screen in points (resolution) and how many colors are available. It also tells BASIC whether you are displaying text only or graphics.

Resolution The number of points on the screen is called the resolution. The greater the number of points, the sharper the image. The 3 reso- lutions are: Low resolution 160 x 200 points Medium resolution 320 x 200 points High resolution 640 x 200 points The horizontal length (x axis) is given first followed by the verti- cal length (y axis). Notice that there are more horizontal points than vertical points. This means that the horizontal points are closer together than the vertical points. The comparison of the number of points per inch vertically to horizontally is called the aspect ratio. The aspect ratio is computed using the following formula: number of number of vertical points horizontal points aspect ratio = - viewing area viewing area height width

The viewing area is the portion of your screen on which images are displayed. It may be smaller than the screen itself.

77 Chapter 8 I Displaying Color and Graphics

The aspect ratio is important when drawing objects on the screen. Keep in mind that the number of horizontal points per inch is greater than the same number of vertical points per inch. Therefore, for example, if you try to draw a square, the perime- ter of the square must contain more horizontal points than verti- cal points. Also, because there is a difference in points per inch among the different screen modes, images that specify the same coordinates do not look the same in different modes.

Colors Colors are selected by numbers that vary, depending on whether you are in a screen mode that supports 2, 4, or 16 color sets. All modes start with the background as black and the foreground as white. Each color set has a defined list of colors called a palette.

The characteristics of each mode are: 2 Color Set is the black and white mode; the background is black and the foreground is white. You cannot change these colors. 4 Color Set has 1 palette of 4 colors available at all times in Screen Modes 4 and 6. The colors are numbered 0-3. Color 0 is the current background color. The other colors are: Number Color 1 cyan 2 magenta 3 white BASIC uses Color 3 as the foreground color if you do not specify a color parameter with graphic statements. Background can be any one of the 16 colors described in the 16 Color Set. See the PALETTE statement for information on changing colors in the palette.

78 Chapter 8 i Displaying Color and Graphics

Screen Mode 1 has 2 palettes of 4 colors. Only 1 palette is avail- able at a time. Color 0 is the current background color. The other colors are: Number Palette 0 Palette 1 1 green cyan 2 , red magenta 3 hrown white 16 Color Set has 1 palette of 16 colors available at all times. The colors are numbered 0-15. The colors available are: Number Color 0 black 1 blue 2 green 3 cyan 4 red 5 magenta 6 brown 7 gray 8 dark gray 9 light blue 10 light green 11 light cyan 12 light red 13 light magenta 14 yellow 15 white The foreground color is initially set to white and the background to black. You can change these colors with the COLOR statement.

Video Pages BASIC sets aside memory to be used for the video display. The amount of memory necessary depends on the screen mode you choose. BASIC initially sets aside 16K for video memory. You can set aside a different amount using the CLEAR statement.

79 Chapter 8 I Displaying Color and Graphics

If you set aside more video memory than is required for the se- lected screen mode, BASIC divides the video memory into pages like pages of a book. You can store information to one page while displaying another. The page being displayed is called the dis- play page and the page being written to is called the active page. BASIC initially sets the display page and the active page to the same page. The amount of memory required for each mode is detailed under “Selecting Screen Modes.”

Selecting Screen Modes You select the screen mode with the SCREEN command. BAS- IC’s graphic screen modes are numbered 1-6.

Screen Mode 0 (Text Mode) Color Set: 16 Graphics Resolution: not available Text Width: 40 or 80 Video Page Size: If WIDTH=40, 2048 bytes, 8 pages max. If WIDTH = 80, 4096 bytes, 4 pages max. You can select different background, foreground and border colors using the COLORlText command. (Border is the last group of pixels around the perimeter of the screen display.) Foreground can be any of the 16 colors in either solid (Colors 8-15] or blink- ing mode (Colors 16-31). Background can be any of Colors 0-7. Border is initially set the same as the background, but can be changed to any of the 16 colors. You can change the text width with the WIDTH command.

Screen Mode 1 Color Set: 4 (2 palettes) Graphics Resolution: medium resolution 320 x 200 Aspect Ratio: 516 Text Width: 40 Video Page Size: 16384 bytes Max. No. of Pages: 8

80 Chapter 8 I Displaying Color and Graphics

Screen Mode 2 Color Set: 2 Graphics Resolution: high resolution 648 x 288 Aspect Ratio: 5112 Text Width: 88 Video Page Size: 16384 bytes Max. No. of Pages: 8

Screen Mode 3 Color Set: 16 Graphics Resolution: low resolution 168 x 208 Aspect Ratio: 513 Text Width: 28 Video Page Size: 16384 bytes Max. No. of Pages: 8

Screen Mode 4 Color Set: 4 Graphics Resolution: medium resolution 328 x 288 Aspect Ratio: 516 Text Width: 48 Video Page Size: 16384 bytes Max. No. of Pages: 8

Screen Mode 5 Color Set: 16 Graphics Resolution: medium resolution 328 x 288 Aspect Ratio: 516 Text Width: 48 Video Page Size: 32768 bytes Max. No. of Pages: 4

81 Chapter 8 I Displaying Color and Graphics

Screen Mode 6 Color Set: 4 Graphics Resolution: high resolution 640 x 200 Aspect Ratio: 5112 Text Width: 80 Video Page Size: 32768 bytes Max. No. of Pages: 4

Specifying Coordinates To draw your graphics images on the display, you must tell BASIC where to put the image on the screen. To do this, you must specify horizontal and vertical points. The horizontal and vertical point numbers are known as the co- ordinates. Coordinates are expressed as x-coordinate, y-coordi- nate or simply x and y. (x is the horizontal point number, and y is the vertical point number.) When you specify specific points as coordinates, they are re- ferred to as absolute coordinates. You may also, in some commands, specify coordinates relative to the current point on the screen. In this case, you specify the number of points from the last graphics point referenced. For ex- ample, if you use the CIRCLE statement to draw a circle, the last point referenced is the center of the circle. If you then exe- cute a LINE statement, using relative coordinates of (0,0) to specify the beginning point, BASIC begins drawing the line at the center of the circle. You may specify positive or negative values as relative coordi- nates. If you specify a negative value, BASIC subtracts it from the coordinate of the last point referenced. If you specify positive values, BASIC adds it to the coordinate of the last point referenced.

82

Chapter 9 INTRODUCTION TO BASIC KEYWORDS

BASIC is made up of keywords. These keywords instruct the computer to perform certain operations. Chapter 10 describes all of BASIC’s keywords. This chapter ex- plains the format used in Chapter 10. It also gives a quick sum- mary of all of BASIC’s keywords.

Format for Chapter 10 Statement Keyword Function Syntax Brief definition of keyword. Detailed definition of keyword and any parameters or argu- ments for that keyword. Example(s1 Sample ProgramW

This format varies slightly, depending on the complexity of each keyword. For instance, some keywords require certain parame- ters or arguments and others do not. Some keywords are followed by defining words that explain how to use the command. The defining words are: Communications used with RS-232 Communications Graphics must be in Screen Modes 1-6 Trap used for event trapping There are more, but they should be self-explanatory.

85 Chapter 9 I Introduction to BASIC Keywords

Some keywords have sample programs that further explain their use or illustrate useful applications that may not be readily ap- parent. Important Note: BASIC for MS-DOS requires that keywords be delimited by spaces. This means that you must leave a space between a keyword and any varia- bles, constants, or other keywords. The only exceptions to this rule are characters that are shown as part of the syntax of the keyword. For example, if you type: DELETE.= BASIC returns a “Syntax error.” You must leave a blank space between the word DELETE and the period.

Terms Used in Chapter 10 line A numeric expression that identifies a BASIC program line. Each line has a number in the range 0 to 65529. integer Any integer expression. It may consist of an integer or of several integers joined by operators. Integers are whole numbers and may be in the range -32768 to 32767 unless otherwise specified. string Any string expression. It may consist of a string, several strings joined by opera- tors, or a string variable. A string is a sequence of characters that is to be taken verbatim. number Any numeric expression. It may consist of a number, several numbers joined by op- erators, or a numeric variable. dummy number A number (or string) used in an expres- or dummy string sion to meet syntactic requirements, but the value of which is insignificant.

86 Chaster 9 I Introduction to BASIC Keywords

Statements A statement tells the computer to perform some operation. The following is a brief description of all BASIC statements: Statement Description AUTO automatically generates line numbers. BEEP produces a sound from the computer speaker. BLOAD loads a memory image file from disk. BSAVE saves a memory image file to disk. CALL calls an assembly-language . CALLS calls an MS-FORTRAN subroutine. CHAIN loads another program and passes varia- bles to that program. CHDIR changes the current directory. CIRCLEiGraphics draws an ellipse on the screen. CLEAR frees memory for data without erasing the program in memory. CLOSE closes access to a disk file. CLS clears the screen. COLORiGraphics selects background and either foreground or palette depending on the screen mode. COLORiText selects foreground, background, and bor- der display colors for Screen Mode 0. COMiTrap enables communications event trapping. COMMON passes variables to a chained program. CONT continues program execution. DATA stores data in your program so that you can access it with a READ statement. DEFDBL defines variables as double precision. DEF FN defines a function according to your specifications. DEFINT defines variables as integers. DEF SEG defines the current segment address. DEFSNG defines variables as single precision. DEFSTR defines variables as strings. DEF USR defines the offset of the entry point for USR routines. DELETE removes program lines from memory. DIM defines the dimensions of an array. DRAWiGraphics draws images on the screen.

87 Chapter 9 I Introduction to BASIC Keywords

Statement Description EDIT edits program lines. END ends a program. ENVIRON modifies BASIC’s Environment String Table. ERASE erases an array. ERL returns the number of the line in which an error occurred. ERR returns an error code after an error. ERROR simulates the specified error. FIELD organizes a direct access buffer. FILES displays names of files and directories on a disk. FOR/NEXT establishes a program loop. GET gets a record from a direct access file or transfers a specific number of bytes from a communications file. GET/Graphics transfers graphic images from the screen to memory. GOSUB transfers program control to a subroutine. GOT0 transfers program control to the specified line. IFITHENIELSE evaluates an expression and performs an operation if conditions are met. INPUT accepts data from the keyboard. INPUT# accepts data from a sequential access de- vice or file. INPUT$ accepts data from the keyboard or a se- quential access file. IOCTL sends control data to a device driver. KEY assigns or displays the current function- key soft values. KEYiTrap enables key-event trapping. KILL deletes a disk file. LCOPY copies all text data on the screen to the printer. LET assigns a value to a variable. (The key- word LET may be omitted.) LINEiGraphics draws a line on the display. LINE INPUT accepts an entire line from the keyboard. LINE INPUT# accepts an entire line from a sequential access file.

88 Chapter 9 I Introduction to BASIC Keywords

Statement Description LIST lists a program to the display or printer. LLIST prints a program on the printer. LOAD loads a program from disk. LOCATE positions the cursor on the screen. LPRINT prints data at the printer. LPRINT USING prints data at the printer in a specified format. LSET moves data (and left-justifies it) to a field in a direct access file buffer. MERGE merges a disk program with a resident program. MID$ replaces a portion of a string. MKDIR creates a directory. NAME renames a disk file. NEW erases a program from RAM. NOISE generates noise through a TV monitor’s speaker. ON COM GOSUB branches to a subroutine when activity occurs on the communication channel. ONERRORGOTO sets up an error-trapping routine. ON/GOSUB evaluates an expression and branches to a subroutine. ONiGOTO evaluates an expression and branches to another program line. ON KEY0 GOSUB branches to a subroutine when a specific key is pressed. ON PEN GOSUB branches to a subroutine when the light pen is activated. ON PLAY0 GOSUB branches to a subroutine when music buffer contains fewer than the specified number of notes. ON STRIGO GOSUB branches to a subroutine when a joystick button is pressed. ON TIMER0 GOSUB branches to a subroutine when timer equals the specified number. OPEN opens a disk file. OPEN “COM opens a communications file. OPTION BASE declares the minimum value for array subscripts. OUT sends a byte to a machine output port.

89 Chapter 9 I Introduction to BASIC Keywords

Statement Description PAINT/Graphics fills in an area of the screen with a se- lected color. PALETTEiGraphics changes the color associated with a color number. PALETTE USING/ changes the colors associated with more Graphics than one color. PCOPY copies one video page to another. PEN/Trap controls light pen event trapping PLAY plays musical notes. PLAYiTrap controls background music event trapping. POKE writes a byte into a memory location. PRESET/Graphics draws a point in color at a specified posi- tion on the screen. PRINT lists data to the display. PRINT USING lists data to the display in a specific format. PRINT# writes data to a sequential access file. PRINT# USING writes data to a sequential access file us- ing the specified format. PSETiGraphics draws a point on the screen at a specified position. PUT/Communications puts a record into a direct access file or transfers a number of bytes to a commu- nications file. PUTiGraphics transfers graphic images from the mem- ory to the screen. RANDOMIZE reseeds the random number generator. READ reads data stored in the DATA statement and assigns it to a variable. REM inserts a remark line in a program. RENUM renumbers a program. RESET closes all open files on all drives. RESTORE restores the DATA pointer. RESUME resumes program execution after an er- ror-handling routine. RETURN returns from a subroutine to the calling program. RMDIR removes a directory. RSET moves data (and right-justifies it) to a field in a direct access file buffer. RUN executes a program.

90 Chapter 9 I Introduction to BASIC Keywords

Statement Description SAVE saves a program on disk. SCREEN sets the screen attributes (text, medium- or high-resolution) to be used by subse- quent statements. SHELL loads and executes another program as a child process. SOUND generates a specific tone for a specified length of time. STOP stops program execution. STRIG enables the STRIG function. STRIG/Trap controls joystick event trapping. SWAP exchanges the values of variables. SYSTEM returns to MS-DOS. TIMER/Trap controls timer event trapping. . TROFF turns off the tracer. TRON turns on the tracer. VIE WIGraphics redefines the screen parameters. VIEW PRINT creates a text viewport to redefine screen parameters. WAIT suspends program execution while moni- toring the status of a machine input port. WHILE ...WEND executes statements in a loop as long as a given condition is true. WIDTH sets the number of characters per line for the screen or printer. WINDOW changes the physicial coordinates of the screen. WRITE prints data on the display. WRITE# writes data to a sequential file.

91 Chawter 9 I Introduction to BASIC Keywords

Functions A function is a built-in subroutine. You may only use it as part of a statement. Most BASIC functions return numeric or string data. Function Description ABS returns the absolute value of a number ASC returns the ASCII code of a character. ATN returns the arctangent of a number. CDBL converts a number to double precision. CHR$ returns the character of an ASCII code. CINT converts a number to an integer. cos returns the cosine of a number. CSNG converts a number to single precision CSRLIN returns the current row position of the cursor. CVD restores data from a direct access disk file to double precision. CVI restores data from a direct access disk file to integer. cvs restores data from a direct access disk file to single precision. DATE$ sets the date or returns the current date. ENVIRON$ returns a string from BASIC’s Environ- ment String Table. EOF checks for end-of-file or an empty commu- nications input queue. ERDEV returns the value of a device error. ERDEV$ returns the name of a device for device error. EXP returns the natural exponent of a number. FIX truncates to a whole number. FRE returns the number of bytes in memory not being used.

92 Chapter 9 I Introduction to BASIC Keywords

Function Description HEX$ converts a decimal value to a hexadeci- mal string. INKEY$ returns the keyboard character. INP returns the byte read from a port. INSTR searches for a specified string. INT returns the integer value of a number. IOCTL$ returns control data from a device driver. LEFT$ returns the left portion of a string. LEN returns the length of the string. LOC returns the current disk file record num- ber or the number of characters in a com- munications input queue. LOF returns the total number of bytes in a disk file or the amount of free space in a communication file input queue. LOG returns the natural logarithm of a number. LPOS returns the position of the print head in the printer buffer. MID$ returns the midportion of a string. MKD$ converts a double precision value to a string for writing it to a direct access file. MKI$ converts an integer value to a string for writing it to a direct access disk file. MKS$ converts a single precision number to a string for writing it to a direct access file. OCT$ converts a decimal value to an octal string.

93 Chapter 9 I Introduction to BASIC Keywords

Function Description PEEK returns a byte from a memory location. PEN returns the coordinates of the light pen. PLAY returns the number of notes in the music buffer. PMAP returns the physical or world coordinates. POINT returns either the color of a point or cur- rent coordinates. POS returns the cursor column position on the display. RIGHT$ returns the right portion of a string. RND returns a random number. SCREEN returns the ASCII code for the character stored at a specific position on the screen. SGN determines the sign of a number SIN returns the sine of a number. SPACE$ returns a string of spaces. SPC prints spaces to the display. SQR returns the square root of a number. STICK returns the coordinates of the joysticks. STR$ converts a number to a string. STRIG returns the status of the joystick buttons. STRING$ returns a string of characters. TAB positions the video cursor or the print head at a specified position. TAN returns the tangent of a number. TIME$ sets the time or returns the current time. TIMER returns the number of seconds since midnight. USR calls an assembly-language subroutine. VAL returns the numeric value of a string. VARPTR returns an offset for a variable or buffer. VARPTR$ returns character form of memory ad- dress of a variable.

94

ChaDter 10 BASIC KEYWORDS

ABS Function

ABS (number)

Returns the absolute value of number. The absolute value of a number is the value without regard to its sign. Absolute values are always positive or zero.

Example PRINT ABS(-66) prints the absolute value of -66 which is 66.

X = ABS(Y) computes the absolute value of Y and assigns it to X. Sample Program

100 INPUT "WHAT'S THE TEMPERATURE OUTSIDE7 (DEGREES F)";TEMP 110 IF TEMP < 0 THEN PRINT "THAT'S" ABS(TEMP1 "BELOW ZERO! BRR!": END 120 IF TEMP = 0 THEN PRINT "ZERO DEGREES! MITE COLD!": END 130 PRINT TEMP "DEGREES ABOVE ZERO! BALMY!": END

97 Chapter 10 I BASIC Keywords

ASC Function

ASC(strZng) Returns the ASCII code for the first character of string. ASC returns the value as a decimal number. If string is null, an "Illegal function call" error occurs.

Example PRINT ASC("A"1 prints 65, the ASCII code for A.

Sample Program You can use ASC to be sure a program is receiving proper input. Suppose you want to write a program that requires the user to input hexadecimal digits (0-9, A-F). To be sure that only those characters are input, and all other characters are excluded, you can insert the following routine. 100 INPUT "ENTER A HEXADECIMAL VALUE";N$ 110 A = ASCCN$) 'get ASCII code 120 IF A>47 AND A<58 OR A>64 AND A<71 THEN PRINT "OK.": GOTO 100 130 PRINT "VALUE NOT OK." : GOTO 100

98 Chawter 10 I BASIC Kevwords

ATN Function

ATN(number)

Returns the arctangent of number. ATN returns the angle (in radians) whose tangent is number. Number must be given in radians. BASIC always returns the result as a single precision number unless you specified the /D switch when starting up BASIC. To convert this value to degrees, use ATN(number*PI), where PI equals 3.141593.

Example PRINT ATN(7) prints the arctangent of 7 which is 1.428899

X = ATN(Y/3) * 57.29578 computes the arctangent of Y13 in degrees and assigns the value to x.

99 Chapter 10 I BASIC Ke.ywords

AUTO Statement

AUTO [line][, increment]

Automatically generates a line number when you are entering a program. AUTO displays a new line number every time you press m. Line is the line number with which you want BASIC to start numbering. To start numbering with the current line number, specify a period (.I as line. If you omit line, BASIC starts with Line 10. Increment is the increment for BASIC to use when generating line numbers. You must precede increment with a comma (,). If you want BASIC to use the increment of the last AUTO state- ment, type the comma but omit increment. If you omit increment and the comma, BASIC uses 10. If you omit line but include in- crement, BASIC begins numbering with Line 0. If BASIC generates a line number that already exists in mem- ory, it displays an asterisk after the number. To save the exist- ing line, press =immediately after the asterisk and AUTO generates the next line number. To turn off AUTO, press [BREAK]. The current line is canceled and BASIC returns to command level.

Examples AUTO generates line numbers beginning with Line 10 using incre- ments of 10. For example, 10, 20, 30 .... AUTO 100,50 generates line numbers beginning with Line 100 using incre- ments of 50. For example, 100, 150, 200 .... AUTO 700, generates line numbers beginning with Line 700 using the in- crement of the last AUTO statement, in this case 50. For exam- ple, 700, 750, 800 ....

100 Chapter 10 I BASIC Keywords

Statement

BEEP BEEP ON BEEP OFF

Produces a sound from the computer’s speaker. BEEP sounds the speaker at 800 Hz for 114 second. You can use BEEP with the SOUND statement to direct sound to the computer’s internal speaker or an external speaker (such as a television’s speaker) or both. BEEP ON : SOUND ON directs sound to both speakers . BEEP OFF : SOUND OFF turns off sound to both speakers. BEEP ON : SOUND OFF directs sound to the internal speaker only. BEEP OFF : SOUND ON directs sound to the exter- nal speaker only. BASIC starts up with BEEP ON and SOUND OFF The BEEP statement is the same as typing PRINT CHR$(7).

Example IF X > 20 THEN BEEP warns the operator with a beep if the variable X is out of range, that is, greater than 20.

101 Chapter 10 I BASIC Keywords

BLOAD Statement

BLOAD pathname[,offsetl

Loads a memory image file into memory. See BSAVE A memory image file is a byte-for-byte copy of what was origi- nally in memory. See BSAVE for information about saving mem- ory image files. Pathname is a standard file specification as defined in Chapter 1. Offset is an integer in the range 0 to 65535. Offset is the num- ber of bytes into the current segment where BASIC loads the im- age. If you omit offset, BASIC uses the offset specified when the file was saved with BSAVE. If you specify offset, BASIC assumes you want to BLOAD at an address other than the one given when the program was saved and uses the current segment address as set by the last DEF SEG statement. Unless you want to load the file into BASIC’s data segment, you must execute the DEF SEG statement before the BLOAD statement. If you used the /M: switch when you loaded BASIC, specify that address as the offset. If you specify an offset without using a DEF SEG statement or the /M: switch, BASIC loads the file at that offset from BASIC’s data segment, destroying BASIC’s workspace. Note: BLOAD does not perform an address range check. It is possible to load a file anywhere in mem- ory. Therefore, you must be careful not to load over BASIC or over the operating system. See the section “Interfacing With Assembly-Language Subrou- tines” in Chapter 11 for more information on loading assembly- language programs.

102 Chapter 10 i BASIC Keywords

You may specify any segment as the target or source for BLOAD or BSAVE. This is a useful way to save and redisplay screen im- ages by saving from or loading to the screen buffer.

Sample Programs Program 1 10 'SAVE A 50 byte image of memory 20 DEF SEG = bHl0 30 FOR I = 256 to 306 40 VLUE = PEEK (1) 50 LPRINT "AT ADDRESS ";I; "WE HAVE A VALUE OF ";VLUE 60 NEXT I 70 BSAVE "prog1",0,50 80 PRINT "Now Run Program 2 to verify that the content5 saved in the file PROGl match those in the printout produced by this program." Program 2 10 'Load a 50 byte file into memory and verify it 20 DEF SEG = &H10 30 BLOAD "progl .bas", 0 40 FOR I = 256 to 306 50 VALUE = PEEKCI) 60 LPRINT "AT ADDRESS ";I; "the loaded value i 5 " ; VALUE 70 NEXT I Program 1 saves a memory image file, and Program 2 reloads that file and prints it.

103 Chapter 10 I BASIC Keywords

BSAVE Statement

%SAVEpathname,offset,length

Saves the contents of an area of memory as a disk file. Pathname is a standard file specification as defined in Chapter 1. Offset is an integer in the range 0 to 65535. Offset is the num- ber of bytes into the current segment where BASIC starts sav- ing. Length is an integer in the range 1 to 65535. This is the length in bytes of the memory image file to be saved. You must specify pathname, offset, and length. If you omit any of them, BASIC returns an error and terminates the save. A memory image file is a byte-for-byte copy of what is in mem- ory. The BSAVE statement lets you save data or programs as memory image files on disk. BSAVE is often used for saving as- sembly language programs, but you can also use it to save data, programs written in other languages, or screen images. When you load BASIC, the data segment (DS) register is set to the address of BASIC’s workspace. You must execute a DEF SEG statement before executing BSAVE, unless you used the /M: switch when you loaded BASIC. Without the DEF SEG state- ment or the /M: switch, BASIC’s workspace could be destroyed.

Sample Program See BLOAD.

104 Chapter 10 I BASIC Keywords

CALL Statement

CALL variable [(parameterlist)]

Transfers program control to an assembly-language subroutine stored at variable. Variable contains the offset into the current segment where the subroutine starts in memory. Variable may not be an array vari- able. The offset must be on a 16-byte boundary. Parameter list contains the variables that are passed to the ex- ternal subroutine. The number, type, and length of the parame- ters being passed must match with the parameters expected by the assembly-language subroutine. If you omit parameter list, BASIC executes an 8086 CALL in- struction. Your assembly-language subroutine should return with a simple RET instruction. When you execute a CALL statement, BASIC transfers control to the subroutine through the address given in the last DEF SEG statement and the segment offset specified by variable. See the section “Interfacing With Assembly-Language ” in Chapter 11 for more details.

Example

100 I=45 : J=100 : K = 55 118 MYROUT = AH0888 120 DEF SEG = AH1700 120 CALL MYROUTCI,J,K) The subroutine, MYROUT, begins at offset 0 in the segment that begins at 1700. The values of I, J, and K are passed to the routine.

105 ChaDter 10 I BASIC Kevwords

CALLS Statement

CALLS variables [(parameterlist)]

Transfers program control to a routine written in MS’” -FOR- TRAN. CALLS works just like the CALL statement, except that CALLS passes arguments as segmented addresses. CALLS uses the address given in most recently executed DEF SEG statement to locate the routine being called.

106 Chawter 10 I BASIC Kevwords

CDBL Function

CDBL(num ber)

Converts number to double precision. This function may be useful if you want to force an operation to be performed in double precision, even though the operands are single precision or integers.

Sample Program 210 A=454.67 220 PRINT A, CDBLCA) When run, this program prints the following: 454.67 454.67001 34277344

107 Chawter 10 I BASIC Kevwords

CHAIN Statement

CHAIN [MERGE] pathnume [,[,line][,ALL] [,DELETE line-line]]

Lets the current program load and execute another program named pathname. Pathname is a standard file specification as defined in Chapter 1. It specifies the program you want to chain. The program must have been previously saved in ASCII format. See SAVE. Line is the line number or variable containing a line number where BASIC begins execution in the chained program. Line is always preceded by a comma (J. If you plan to use the ALL or DELETE options and do not specify a line number, you must specify a comma for line. This keeps BASIC from evaluating ALL and DELETE as variables. If you omit line, BASIC begins execution at the first program line of the chained program. The ALL option tells BASIC to pass every variable in the cur- rent program to the chained program. If you omit ALL, the cur- rent program must contain a COMMON statement to pass variables to the chained program. If chained programs chain subsequent programs and pass variables, each new program must contain either the ALL option or the COMMON statement. The MERGE option overlays the lines of the chained program with the current program. See the MERGE statement to under- stand how BASIC overlays (merges) program lines. The DELETE option deletes lines in the overlay so that you can merge in a new overlay.

Ex amples CHAIN "pr092" loads prog2, chains it to the program currently in memory, and begins executing it. CHAIN "subprog. ba5", ,ALL loads, chains and executes subprog.bas. The values of all the variables in the current program are passed to subprog.bas.

108 Chapter 10 I BASIC Keywords

Sample Program 1 10 REM THIS PROGRAM DEMONSTRATES CHAINING USING COMMON TO PASS VARIABLES. 20 REM SAVE THIS MODULE ON DISK AS "PROGI .BAS" USING THE A OPTION. 30 DIM ASC2),BS(2) 40 COMMON AS0,BSO 50 AS

109 Chapter 10 I BASIC Keywords

Sample Program 2 Enter NEW and this program: 10 REM THIS PROGRAM DEMONSTRATES CHAINING USING THE MERGE AND ALL OPTIONS. 20 A$="MAINPROG.BAS" 30 CHAIN MERGE "overlayl", 1000, ALL 40 END Save this program as mainprog.bas, using the A option. Enter NEW, and then type: 1000 PRINT A$;" HAS CHAINED TO OVERLAY1 .BAS." 1010 A$ = "overlayl .bas" 1020 B$ = "overlay2.ba5" 1030 CHAIN MERGE "overlay2.ba5", 1000, ALL, DELETE 1020 - 1040 1040 END Save this program as overlayl.bas, using the A option. Enter NEW, and then these lines:

1000 PRINT A$; " HAS CHAINED TO ";E$;"." 1010 END Save this program as overlay2.bas, using the A option. Load mainprog.bas and run it. Your screen should display: MAINPROG.BAS HAS CHAINED TO OVERLAY1.BAS. OVERLAY1.BAS HAS CHAINED TO OVERLAY2.BAS.

Hints: The CHAIN statement with the MERGE option leaves the files open and preserves the current OPTION BASE setting.

0 The CHAIN statement without the MERGE option does not preserve variable types or user-defined functions for use by the chained program. That is, any DEFINT, DEFSNG, DEFDBL, DEFSTR, or DEF FN statements containing shared variables must be restated in the chained program.

0 When using the MERGE option, place user-defined functions before any CHAIN MERGE statements in the program. Oth- erwise, the user-defined functions will be undefined after the merge is complete.

0 CHAIN automatically executes a RESTORE before running the chained program. The next READ statement starts at the first item of the first DATA statement.

110 Chapter 10 I BASIC Keywords

CHDIR Statement

CHDIR dirpath

Changes the current directory. Dirpath is a standard directory specification as defined in Chap- ter 1.

Examples CHDIR "B: \f?CCTS\RECVBLE" changes the currect directory on Drive B to ACCTS\RECVBLE. CHDIR "\RECORDS" changes the directory on the current drive to RECORDS. CHDIR ". ." changes the current directory to the parent directory of the cur- rent directory.

111 Chapter 10 I BASIC Keywords

CHR$ Function

CHR$(code)

Returns the character corresponding to an ASCII or control code. Code is any ASCII or control code. CHR$ is the inverse of the ASC function and is commonly used to send a special character to the display. See Appendix B for a list of ASCII codes.

Example PRINT CHR$<35) prints the character corresponding to ASCII code 35, which is #.

Sample Program The following program lets you investigate the effect of printing ASCII codes on the display. 100 CLS 110 INPUT "TYPE IN THE CODE"; C 120 PRINT "CHR$

112 Chapter 10 i BASIC Keywords

CINT Function

C INT(num ber)

Converts number to integer. Number must be in the range -32768 to 32767. CINT rounds the fractional portion of number to make it an integer. See also FIX and INT, which also return integer values. Examples PRINT CINT(1.56) prints 2. PRINT CINTC-1.67) prints -2.

113 Chapter 10 I BASIC Keywords

CIRCLE/Graphics Statement

Draws an ellipse on the screen with the specified center and radius. (x,y) specify the coordinate for the center of the circle. x is the horizontal coordinate and y is the vertical coordinate. Color indicates the color of the ellipse and must be a valid num- ber in the current color set. The STEP option tells BASIC that the (x,y)coordinates are rela- tive to the last point referenced. The possible ranges for x, y, and color depend upon the current screen mode as defined in Chapter 8, “Displaying Color and Graphics. ” Radius is the major axis of the ellipse. Start and end are the beginning and ending angles in radians and must be in the range -6.283186 to 6.283186, or -2 * PI to 2 * PI, where PI equals 3.141593. If you specify a negative start or end angle, the ellipse is connected to the center point with a line, and the angles are treated as if they were positive. Aspect is the ratio of the x-radius to the y-radius in terms of co- ordinates. If aspect is less than 1, radius is the x-radius and is measured in points in the horizontal direction. If aspect is greater than 1, radius is the y-radius and is measured in points in the vertical direction. If you omit aspect, BASIC uses the de- faults for the current screen mode as defined in Chapter 8. When you use the default, BASIC draws a circle.

114 Chapter 10 I BASIC Ke.ywords

To draw an ellipse that is wider than it is high, use an aspect ratio that is less than the default value for that screen mode. The smaller the aspect ratio you specify, the wider and shorter the ellipse. For example, in Screen Mode 1, an aspect ratio of 1/2 gives you an ellipse like this:

To draw an ellipse that is higher than it is wide, use an aspect ratio that is larger than the default value for that screen mode. The larger the aspect ratio that you use, the taller and thinner the ellipse. For example, in Screen Mode 1, an aspect ratio of 716 draws an ellipse like this:

115 Chapter 10 I BASIC Keywords

See Chapter 8 for more information on aspect ratio and specify- ing coordinates.

Examples 10 SCREEN 1 20 CIRCLE (150,100),50 draws a circle with the center at point 150,100 and a radius of 50.

Sample Program 10 SCREEN 1 20 FOR 1=0 TO 3 30 CLS 40 CIRCLE (150,100),50,1 50 PAINT (150,1001,I 60 FOR Q=l TO 300:NEXT Q 70 NEXT I 80 SCREEN 0

116 Chapter 10 I BASIC Ke-ywords

CLEAR Statement

CLEAR [,memory location.] [,stack space][,uideo memory1

Frees memory for data without erasing the program currently in memory. CLEAR erases all arrays, sets numeric variables to zero and string variables to null, and erases any information set using a DEF statement, such as DEF SEG and DEF FN. CLEAR also turns off the SOUND, PEN, and STRIG functions and resets the music background. Since CLEAR initializes all variables, place it near the begin- ning of your program, before any variables have been defined and before any DEF statements. Memory location must be an integer. It specifies the highest memory location available for BASIC. The default is the current top of memory as specified with the /M: switch when BASIC was loaded. This option is useful if you will be loading an assembly- language subroutine, because it prevents BASIC from using that memory area. Stack space also must be an integer. This sets aside memory for temporarily storing internal data and addresses during subrou- tine calls and during FOR/NEXT loops. If you omit stack space, BASIC sets aside 768 bytes or one-eighth of the memory avail- able, whichever is smaller. BASIC displays an “Out of memory” error if stack space for program execution is insufficient. Video memory is an integer that specifies the amount of memory to be set aside as video memory. For graphics modes, if the vdeo memory you specify is not a multiple of 16K bytes (16384 bytes), BASIC rounds it down to the nearest multiple of 16K. If you omit video memory, BASIC sets aside 16K. The video memory page size for each screen mode is described in Chapter 8, “Dis- playing Color and Graphics.”

117 Chapter 10 I BASIC Keywords

If you set video memory larger than the required page size, BASIC divides the assigned memory into pages based on the page size requirement. For example, if you set aside 32K for video memory for Screen Mode 1, BASIC divides the video mem- ory into 2 pages (32/16=2). See Chapter 8, SCREEN, and PCOPY for more on video pages. Note: BASIC allocates string space dynamically. BASIC displays an “Out of string” space error if no free memory is left for BASIC. Ex ample s CLEAR clears all variables and closes all files. CLEAR, 45000 clears all variables and closes all files; then makes 45000 the highest address BASIC may use to run your programs. CLEAR, 61000, 300 clears all variables and closes all files; then makes 61000 the highest address BASIC may use to run your programs, and allo- cates 300 bytes for stack space. CLEAR ,,,32768 sets aside 32K for video memory.

118 Chapter 10 I BASIC Keywords

Statement

CLOSE [buffer,...I

Closes access to a disk file. Buffer is the number assigned to the file when you opened it. If you omit buffer, BASIC closes all open files. This command terminates access to a file through the specified buffer. If buffer has not been assigned by an OPEN statement, then CLOSE buffer has no effect. Do not remove a disk that contains an open file. Close the file first, because the last records may not have been written yet. Closing the file writes the data currently in the buffer if it has not been written already. Note that CLEAR, END, NEW, RESET, and SYSTEM automat- ically close all files when executed. See also OPEN and Chapter 7, “Disk Files.”

Examples CLOSE 1, 2, 8 terminates the file assignments to Buffers 1, 2, and 8. You can now assign these buffers to other files with OPEN statements.

CLOSE FIRST% + COUNT% terminates the file assignment to the buffer specified by the sum FIRST% + COUNT%.

119 Chapter 10 I BASIC Keywords

CLS Statement

CLS

Clears the screen and returns the cursor to the home position. Home is Row 0, Column 0, or in other words, the upper left cor- ner of the screen. If a viewport is active, CLS clears only the active viewport. To clear the entire screen, you must use VIEW to redefine the en- tire screen before using CLS. Changing the screen mode with SCREEN or changing the width with WIDTH automatically clears the screen. You can also clear the screen by typing [CTRL][T]or [CTRL)[HOME].

Sample Program 540 CLS 550 FOR I = 1 TO 24 560 PRINT STRING$(79,33) 570 NEXT I 580 GOTO 540

~ 120 Chapter 10 I BASIC Keywords

COLOR/Graphics Statement Screen Mode 1: COLOR [background][,[palette11 Screen Modes 3-6: COLOR [foreground][ , [ background11

Selects the background color and either the palette or foreground colors, depending on the current screen mode. Background specifies the background and border colors. It may be 0-15 as described in Chapter 8, “Displaying Color and Graphics.” Foreground specifies the foreground color. In Screen Modes 3 and 5, foreground may be Colors 1-15. In Screen Modes 4 and 6,fore- ground may be Colors 1-3. Specifying 0 as the foreground color causes an “Illegal Function Call” error. Colors are described in Chapter 8, “Displaying Color and Graphics.” Note: If you set foreground the same as background, the characters are invisible. Palette specifies which palette to use and may be 0 or 1 to select Palette 0 or Palette 1. After executing the COLORiGraphics statement, you may use the PALETTE and PALETTE USING statements to change any or all these values. See PALETTE AND PALETTE USING. If you omit any parameters, BASIC assumes the default values or previous values.

Examples 10 COLOR 9,0 sets background to light blue and selects Palette 0 in Screen Mode 1. 20 COLOR ,I background retains its previous value. Palette 1 is selected in Screen Mode 1.

121 ChaDter 10 I BASIC Keywords

Sample Programs 5 SCREEN 5 10 COLOR 12,l 20 LINE (0,0) - (319,199) Line 10 selects a light red foreground with a blue background. Line 20 draws a light red diagonal line on the display. 5 SCREEN 1 10 COLOR 3,0 20 LINE (0,0) - (319,199) Line 10 selects a cyan background and Palette 0. Line 20 draws a brown diagonal line on the video display. If you select Palette 1 in Line 10, Line 20 draws a white diagonal line.

122 Chapter 10 I BASIC Ke.ywords

C OLOR/Text Statement

COLOR [foreground], [ background][, border11

Selects the display colors for the foreground, background, and border for displaying in text mode. To be in text mode, you must have selected Screen Mode 0 with the SCREEN statement. Foreground is an integer in the range 0 to 31, specifying the foreground color. Colors 16-31 cause blinking foreground. To fig- ure the color, add 16 to the color numbers defined in the 16 Color Set in Chapter 8. Background is an integer in the range 0 to 7, specifying the background color. COLORiText can use any of the colors in the 16 Color Set as fore- ground. See Chapter 8 for more information. Note: If you set foreground the same as background, the characters are invisible. Border is an integer in the range 0 to 15, specifying the border color. If you omit any parameter, BASIC assumes the previous values or the default values.

Examples COLOR 0,7 selects black characters on a white background. COLOR 1 ,0 selects blue characters on a black background. COLOR 4,0 selects red characters on a black background.

123 Chapter 10 I BASIC Ke.ywords

COM Statement

COM(channe1) action

Turns on, turns off, or temporarily halts the trapping of activity on the specified communications channel. Channel selects communications channel 1 or 2. Action may be any of the following: ON enables communications trapping. OFF disables communications trapping. STOP temporarily suspends communications trapping. Use the COM statement in a communications trap routine with the ON COM() GOSUB statement to detect when characters have come into the communications channel. The COM( ) ON statement turns on the trap. BASIC checks after every program statement to see if a character has come into the communications channel. If so, BASIC transfers program control to the line number specified in the ON COM() GOSUB statement . The COM( ) STOP statement temporarily halts communications trapping. If activity occurs on the communications channel, BASIC does not transfer program control to the ON COM( 1 GO- SUB statement until you turn on communications trapping again by executing a COM() ON statement. BASIC remembers that activity took place and branches to the subroutine immedi- ately after communications trapping is turned on again. The COM( ) OFF statement turns off communications activity trapping. BASIC does not remember if activity took place when communications trapping is turned on again. We recommend that your trap routine read the entire message from the communications port. Do not use a COM trap to trap a single character message because the amount of time required to trap and read every character can cause the communications buffer to overflow.

124 Chapter 10 I BASIC Keywords

See ON COM( ) GOSUB for more information about communica- tions trapping.

Example 10 COM(1) ON 20 PRINT "NO ACTIVITY" 30 ON COM(1 1 GOSUB 100 40 GOT0 20

100 PRINT "YOU ARE RECEIVING DATA"

200 RETURN Line 10 turns on a communications trar, on Channel 1. If char- acters are received on the communications channel, program control transfers to the subroutine beginning at Line 100. If there is no activity on the communications channel, Line 20 prints a message, and Line 40 keeps the program in a loop until there is activity on the communications channel.

125 Chapter 10 I BASIC Keywords

COMMON Statement

COMMON uariabZe[,uariabZe,.. .I

Passes Variables to a chained program. Both programs in the chain should contain a COMMON state- ment. COMMON may appear anywhere in a program, but we recommend using it at the beginning. The same variable cannot appear in more than one COMMON statement in a single program. The size and order of the vari- ables must be the same in the programs being chained. To spec- ify array variables, append “0” to the variable name. If you are passing all variables, use CHAIN with the ALL option and omit the COMMON statement. Note: Array variables used in a COMMON statement must have been declared in a DIM statement. See the CHAIN statement for more information on passing variables.

Example 90 DIM D(50) 100 COMMON A, E, C, DO,G$ 110 CHFI IN ”PROG3”, 10 Line 100 passes variables A, B, C, D, and G$ to the CHAIN command in Line 110.

126 Chawter 10 I BASIC Kevwords

CONT Statement

CONT

Resumes program execution. You may only use CONT if the program has been stopped by [CTRL][BREAK] or the execution of a STOP or an END statement. CONT is primarily a tool. During a break or stop in execution, you may examine variable values (using PRINT) or change these values. Then type CONT (ENTER] to continue execu- tion with the new variable values. You cannot use CONT after editing your program lines or other- wise changing your program. CONT is also invalid after execu- tion has ended normally. See the STOP statement to terminate execution and the GOT0 statement to begin execution at a specific line number. Example 10 INPUT "ENTER 3 NUMBERS a,b,c";A, B, C 20 K=A"2 30 L=BA3/.26 40 STOP 50 M=C+40*K+100: PRINT M Run this program. BASIC prompts for 3 numbers. Type: 1, 2, 3 (ENTERJ The computer displays "Break in 40." You can now enter a BASIC statement as a command. For example: PRINT L [ENTER] displays 30.76923. You can also change the value of A, B, or C. For example, to change the value of C, type: c=4 Now type: CONT [ENTER] and BASIC displays 144.

127 Chapter 10 I BASIC Ke.ywords cos Function

COS(num ber)

Returns the cosine of number. COS returns the angle (in radians) whose sine is number. Number must be given in radians. If number is in degrees, you can convert it to radians by using COS (number * PI/180), where PI equals 3.141593. BASIC always returns the result as a single precision number unless you specified the /D switch when starting up BASIC.

Examples PRINT COS(5.8) - COS(85 * .42) prints the arithmetic (not trigonometric) difference of the 2 cosines.

Y = COSCX .0174533) stores in Y the cosine of X, if X is an angle in degrees.

128 Chapter 10 I BASIC Keywords

CSNG Function

C SNG(num ber)

Converts number to single precision. .BASIC rounds the number when converting it to single precision. Example PRINT CSNGC.1453885509) prints .1453885 Sample Program

280 VU = 876.2345678U 290 PRINT V#, CSNGCV#) When run, this program prints: 876.2345678 876.2346

129 Chapter 10 I BASIC Keywords

CSRLIN Function

CSRLIN

Returns the current row position of the cursor. See the POS function to return the current column position and the LOCATE statement to set the row and column positions. Example 10 PRINT "This is Line": 20 PRINT CSRLIN

130 Chapter 10 I BASIC Keywords

CVD, CVI, CVS Function

CVD(8- byte string) CVI(2-byte string) CVS(4-byte string)

Converts string values to numeric values. These functions restore data to numeric form after it is read from the disk. Typically, the data has been read by a GET state- ment and is stored in a direct access file buffer. CVD converts an 8-byte string to a double precision number. CVS converts a 4-byte string to a single precision number. CVI converts a 2-byte string to an integer. CVD, CVI, and CVS are the inverse of MKD$, MKI$, and MKS$, respectively.

Examples

A# = CVD

Sample Program This program reads from the file test.dat, which is created in the sample program for the MKD$, MKI$, and MKS$ functions. 1420 OPEN "R", 1, "te~t.dat", 14 1430 FIELD 1, 2 AS I1$, 4 AS I2$, 8 AS 13s 1440 GET 1 1450 PRINT CVI

131 Chapter 10 I BASIC Keywords

DATA Statement

DATA constant [,constant,.. .]

Stores numeric and string constants to be accessed by a READ statement. This statement may contain as many constants (separated by commas) as can fit on a line (a maximum of 255 characters in- cluding the word DATA, commas, and spaces). DATA statements may appear anywhere it is convenient in a pro- gram. BASIC reads DATA statements sequentially, starting with the first constant in the first DATA statement and ending with the last item in the last DATA statement. String constants containing delimiters, such as leading or trail- ing blanks, colons, or commas, must be enclosed in double quota- tion marks when used in DATA statements. The data types in a DATA statement must match with the vari- able types in the corresponding READ statement, otherwise, BASIC displays a “Syntax error.” Note that numeric expressions are not allowed in a DATA state- ment. To reread DATA statements from the beginning, use a RE- STORE statement before the next READ statement.

132 Chapter 10 I BASIC Keywords

Examples DATA NEW YORK, CHICAGO, LOS ANGELES, PHILADELPHIA, DETROIT stores 5 string data items. Quotation marks are not needed since the strings contain no delimiters and the leading blanks are not significant. DATA 2.72, 3.14, 0.01745, 57.29578 stores 4 numeric data items. DATA "SMITH, T.H.",38, "THORN, J.R.",41 stores both types of constants. Quotation marks are required around the first and third items because they contain commas.

Sample Program 1 0 PR I NT "C I TY" , "STATE", "2 IP" 20 READ CS,S$,Z 30 DATA "DENVER ,", COLORADO, 8021 1 40 PRINT CS,SS,Z This program reads string and numeric data from the DATA statement in Line 30.

133 Chapter 10 I BASIC Ke-ywords

DATE$ Function

DATE$[ = string]

Sets the date or retrieves the current date. String is a literal, enclosed in quotation marks, that sets the current date by assigning a value to DATE$. If you omit string, BASIC retrieves the current date.

Setting the Date BASIC uses the same dates as MS-DOS, January 1, 1980 to De- cember 31, 2099. You may use either a slash or a hyphen to sep- arate the month, day, and year. You may use any of the following forms to set the current date: mmlddlyy mmlddlyyyy mm-dd-yy mm -dd-YYYY The month (mm)may be any number 01-12. The day (dd)may be any number 01-31. The year (yy or yyyy) may be 01-99 or 1980-2099. You may omit leading zeroes for the month and day. If you only supply 2 digits for the year, BASIC precedes these digits with 19.

Retrieving the Date Regardless of the form you use to set the date, BASIC retrieves the date in the following form: mm-dd-y yy y The month and day are always returned as 2 digits, BASIC in- serts zeroes as necessary.

134 Chapter 10 I BASIC Ke.ywords

Examples

DATES = "9/6/84" DATE$ = "9/6/1984" DATES = "9-6-84" DATES = "9-6-1 984" All the above set the current date as 09-06-1984. PRINT DATES prints the current system date.

CURDATES = DATES assigns the value of the current date to the variable CURDATE$.

135 Chapter 10 I BASIC Keywords

DE FDBL/INT/SNG/STR Statement

DEFDBL letter[,letter,...I DEFINT letter[,letter,...I DEFSNG letter[,letter,...I DEFSTR letter[,letter,... 1

Defines any variables beginning with letteris) as: double preci- sion (DBL), integer (INT), single precision (SNG), or string (STR). You may specify letter as a range of letters. For example, A-J. Remember, a type declaration tag always takes precedence over a DEF statement. Examples DEFDBL L-P classifies all variables beginning with the letters L through P as double precision variables. DEFSTR A classifies all variables beginning with the letter A as string variables. DEFINT I-N, W,Z classifies all variables beginning with the letters I through N, W, and Z as integer variables. DEFSNG I, Q-T classifies all variables beginning with the letters I or Q through T as single precision variables.

136 Chawter 10 I BASIC Kevwords

DEF FN Statement

DEF FNname [(argument list)]=expression

Defines mme as a function according to the expression. Name must be a valid variable name. The type of variable you use determines the type of value the function returns. For exam- ple, if you use a single precision variable, the function returns single precision values. This name, preceded by FN, is the name of the function when you call it. Argument list is a list of dummy variables used in expression. They are replaced on a one-to-one basis with the variables or values given when the function is called. If you enter several variables, separate them with commas. These variables do not affect variables in your program with the same name. Expression defines the operation to be performed. A variable used in a function definition may or may not appear in argument list. If it does, BASIC uses the value given when the function is called to perform the function. Otherwise, it uses the current value of the variable. Once you define and name a function (by using this statement), you can use it as you would any BASIC function. Examples

DEF FNR = RND (1)*89+10 defines a function FNR to return a random value between 10 and 99. Notice that the function can be defined with no arguments. 210 DEF FNW#

137 Chapter 10 I BASIC Keywords

DEF SEG Statement

DEF SEG[ = address]

Assigns the current segment address. The segment address is used by BLOAD, BSAVE, CALL, PEEK, POKE, and USR. Address is a number in the range 0 to 65535, and may be speci- fied as an integer or a hexadecimal value. If you specify a num- ber outside this range, BASIC returns an “Illegal function call” error and uses the previously set address. If you omit address, BASIC sets the current segment address to its data segment (DS). If you specify address, do so on a 16-byte boundary. BASIC shifts the value to the left 4 bits, which is the same as multiply- ing it by 16 decimal (10 hexadecimal). Note: BASIC does not check the validity of the result- ant segment + offset address. When you load BASIC, the data segment (DS) register is set to the address of BASIC’s workspace. You must, therefore, execute a DEF SEG statement before executing BLOAD, BSAVE, PEEK, POKE, USR, or CALL (unless you used the /M: switch when you loaded BASIC). Without the DEF SEG statement or the iM: switch, BASIC’s workspace could be destroyed. If you execute a DEF SEG to change the DS register, you must execute another DEF SEG to restore the DS register to BASIC’s data segment (DS). Separate DEF and SEG with a space. Otherwise, BASIC inter- prets it as the variable DEFSEG.

138 Chapter 10 I BASIC Ke.ywords

See the section “Interfacing With Assembly-Language Subrou- tines” in Chapter 11 for more information. Ex ample 10 DEF SEG=&HB800 ’Set segment to &800 Hex 20 DEF SEG ‘Restore to BASIC data segment sets the DS register to B8000 hexadecimal (B800H * 10H), which is its default value.

139 Chapter 10 I BASIC Keywords

DEF USR Statement

DEF USR[number]= offset

Defines the user number and segment offset of a subroutine to be called by the USR function. Number may be an integer in the range 0 to 9. If you omit num- ber, BASIC assumes USR0. Offset is an integer in the range 0 to 65535. BASIC computes where the subroutine begins in memory by adding the offset to the current segment address as set by DEF SEG. BASIC trans- fers control to this address when you execute the USR function. If the subroutine is not in BASIC’s data segment, you must exe- cute a DEF SEG statement before the USR function. A program may contain any number of DEF USR statements, al- lowing access to as many subroutines as necessary. However, only 10 definitions may be in effect at one time. See the section “Interfacing With Assembly-Language Subrou- tines” in Chapter 11 and USR in this chapter for more details.

Examples DEF USR3 = 6H0020 DEF SEG = &HI700 USR3 begins at 20H bytes into the current data segment which is set at 1700 hexadecimal. When your program calls USR3, con- trol branches to your subroutine beginning at absolute address 17020. (1700*10+ 20).

140 Chapter 10 I BASIC Ke.ywords

DELETE Statement

DELETE linel -line2

Deletes linel through line2 of the program in memory. If you omit linel, BASIC deletes from the beginning of the pro- gram. If omit ZineZ, BASIC deletes to the end of the program. If you specify a line number that does not exist, BASIC displays an “Illegal function call” error. You can substitute a period (.) for either linel or line2 to indicate the current line number.

Examples DELETE 70 deletes Line 70 from memory. DELETE .-I10 deletes from the current line to Line 110, inclusive. DELETE -40 deletes all program lines up to and including Line 40 DELETE 150- deletes program lines starting at and including 150 to the end of the program.

141 Chapter 10 I BASIC Keywords

DIM Statement

DIM array(dimenswn)[,array(dimnsion),.. .I

Sets aside storage for arrays with the dimensions you specify. Array is the variable name of the array. It may be a string, inte- ger, single precision, or double precision variable. Dimension is 1or more integer numbers separated by commas that define the dimensions of the array. The lowest element in a dimen- sion is always zero, unless an OPTION BASE 1 statement is executed. When you execute the DIM statement, BASIC reserves space in memory for each element of the array. Each element is initially set to zero for numeric arrays or null for string arrays. If you do not dimension an array, the maximum number of ele- ments it can have is 11 (0-10). Remember that arrays are completely independent of variables that have the same name; that is MN and MNO are unique. For more information on arrays, see Chapter 6.

Examples DIM AR(100) sets up a 1-dimensional array ARO, containing 101 elements: AR(0), AR(l), AR(2),..., through AR(100). DIM Ll%(8,25) sets up a 2-dimensional array Ll%(), containing 9 x 26 integer elements.

142 Chwter 10 I BASIC Keywords

DRAW/Graphics Statement

DRAW string

Draws an image on the screen String specifies 1 or more of the movement commands listed be- low. String must be enclosed in quotation marks.

Movement commands Each of the following movement commands begins movement from the current graphics position, which is the coordinate of the last graphics point plotted with another graphics command, such as LINE or PSET. The current position defaults to the center of the screen if no previous graphics command has been executed. Moves up n points. Moves down n points. Moves left n points. Moves right n points. Moves diagonally up and right n points. Moves diagonally down and right n points. Moves diagonally down and left n points. Moves diagonally up and left n points. Moves to point x,y. If you precede x with a plus ( + ) or minus (-1 sign, DRAW assumes it is a relative posi- tion. Otherwise, it is an absolute position.

143 Chapter 10 I BASIC Keywords

Prefix Commands The following prefix commands can precede the movement com- mands. Prefix commands must be enclosed in quotation marks. B plots no points after move. N returns to original position when move is complete. Aangle sets angle of move. Angle may be in the range 0 to 3 (0 = 0 degrees, 1 = 90 degrees, 2 = 180 degrees, and 3 = 270 degrees). Ccolor sets color as described in Chapter 8, “Displaying Color and Graphics.” Pcdor, sets the color to paint and border color at which to border stop painting. Possible colors are described in Chapter 8, “Displaying Color and Graphics.” Sfactor sets scale factor. Factor is an integer in the range 1 to 255. The scale factor is factor divided by 4. For exam- ple, if factor is 2, the scale factor is 214. To determine the actual travel distance, multiply the scale factor by the number in the movement commands. If you do not specify a factor, BASIC uses 4, which sets the scale to 1. TAangle moves at the specified angle. Angle is in the range -360 to +360. If angle is positive, movement is coun- terclockwise. If angle is negative, movement is clockwise. Xuariable;executes a substring. The X command lets you execute a second substring from the first string, much like the GOSUB statement. Variable is a string variable in your program that contains the substring you want to execute. Variable may contain an X command to exe- cute another substring. The semicolon after variable is required. In the prefix commands, the numeric arguments can be con- stants or variables. If you use a variable name as a numeric ar- gument, you must follow it with a semicolon.

144 Chapter 10 I BASIC Keywords

Sample Programs 5 SCREEN 3 10 U$ = "U30;": D$= "D30;": L$ = "L40;": R$ = "R40 . II 20 Six$ = U$ + R$ + D$ + L$ 30 DRAW "XBOX$;" 40 A$=INKEY$ : IF A$=""THEN 40 50 SCREEN 0 draws a rectangle on the screen. 5 SCREEN 3 10 U$ = "U30.": D$= "D30.": L$ = 'aL40.'1: R$ =

"R40 ;I' 20 DRAW "XU$; XRB; XDS; XL$;" 30 A$=INKEY$: IF A$=""THEN 30 40 SCREEN 0 draws the same rectangle as the previous example. 10 SCREEN 1 20 DRAW "L40 E20 F20" 30 A$=INKEY$: IF A$=""THEN 30 40 SCREEN 0 draws a triangle on the screen.

145 Chapter 10 I BASIC Keywords

EDIT Statement

EDIT line

Enters the Edit mode. BASIC displays line for editing. You can substitute a period (.) for line to indicate the current line number. See Chapter 4, “General Information,” for more information on editing and special keys.

Examples EDIT 100 enters Edit mode at Line 100. EDlT enters Edit mode at current line.

146 Chapter 10 I BASIC Ke.ywords

END Statement

END

Ends program execution and closes all files. You may place this statement anywhere in the program. It forces execution to end at some point other than the last sequential line. An END statement at the end of a program is optional.

Sample Program 40 INPUT S1, S2 50 GOSUB 100 55 PRINT H 60 END 100 H=SQR

147 Chapter 10 I BASIC Ke,ywords

ENVIRON Advanced Statement

ENVIRON “parameter id = text” [;“parameter id = text”,. . .I

Lets you modify BASIC’s Environment String Table, such as changing the PATH parameter for a child process or passing pa- rameters to a child process. BASIC’s Environment String Table is initially empty. Parameter Id is the name of the parameter. Text is the new parameter text. It must be separated from pa- rameter id by an equal sign (=) or a space. BASIC reads the first nonblank, nonequal sign character after the parameter id as the text. If you omit text, or specify a null string or a semicolon ( ; ), BASIC removes the parameter from the Environment String Table and compresses the table. Parameter id = text must be enclosed in quotation marks and be typed in all uppercase characters. When you change a parameter in the Environment String Table, BASIC deletes the old parameter and adds the new one to the end of the table. If the parameter does not exist in the Environment String Table, BASIC adds it to the end of the table. For more information on Environment String Tables, see the Pro- grammer’s Reference manual for your computer. It is available at your Radio Shack Computer Store.

Examples ENVIRON “PATH=A: \” sets the default path to the root directory on Drive A. E NV I R 0 N “SAL E S = MY S A L E S” sets the name SALES equal to MYSALES. The Environment String Table now looks like this: PATH=A:\;SALES=MYSALES

148 Chapter 10 I BASIC Keywords

ENVIRON$ Advanced Function

ENVIRON$ [('>parameter id")] [(number>l

Returns the specified environment string from BASIC's Environ- ment String Table. Parameter id specifies the parameter for which to search. ENVI- RON$ returns the text string for parameter id. If the parameter does not exist or does not contain a text string, ENVIRON$ re- turns an empty string. Parameter id must be enclosed in quota- tion marks. If you omit parameter id, you must specify number. Number specifies which parameter to return by its position within the table. ENVIRON$ returns the text string for the number parameter. If there is not a parameter in that position, ENVIRON$ returns an empty string. If you omit number, you must specify parameter id. Parameter id and number are mutually exclusive, only one may be specified on the command line. For more information on the Environment String Tables, see the Programmer's Reference manual for your computer. It is available at your Radio Shack Computer Store.

Example If you execute the following ENVIRON statements:

ENVIRON "PATH=A: \I' ENVIRON "SALES=MYSALES" the Environment String Table looks like this: PATH=A:\;SALES=MYSALES The command PRINT ENVIRON$("PATH") prints A: \ .

The command PRINT ENVIRON$(B) prints SALES = MYSALES.

149 Chapter 10 I BASIC Keywords

EOF Function

E OF(buffer)

Detects the end of a file. Buffer is the number assigned to the file when you opened it. It must access an open file. This function checks to see whether all characters up to the end- of-file marker have been accessed so that you can avoid "Input past end" errors during sequential input. When used with sequential access files, EOF returns 0 (false), when the end-of-file record has not been read yet, and -1 (true), when it has been read. When used with direct access files, EOF returns -1 (true) if the last executed GET statement was unable to read an entire record because of an attempt to read beyond the physical end of the file. Sample Program The following sequence of lines reads numeric data from &ta.txt into the array AO. When the last data character in the file is read. the EOF test in Line 30 is true. so the program branches out of the disk access loop. 1470 DIM A(100) 'ASSUMING THIS IS A SAFE VALUE 1480 OPEN "I", 1, "data.txt" 1490 I% = 0 1500 IF EOF(1 1 THEN GOTO 1540 1510 INPUT#I, A(I%) 1520 I% = I% + 1 1530 GOTO 1500 1540 REM PROG. CONT. HERE AFTER DISK INPUT

150 Chapter 10 I BASIC Keywords

E OF/Communications Function

EOF(buffer)

Detects an empty input queue for communications files. Buffer is the number assigned to the file when you opened it. It must access an open file. The value EOF returns depends on the mode (ASCII or binary) in which the file was opened. In ASCII mode, EOF returns a -1 (true) if a CONTROL-Z is received. EOF remains true until the device is closed. In binary mode, EOF returns a -1 (true) when the input queue is empty. EOF becomes false when the input queue is not empty.

Sample Program These lines are useful in a program when you want to run the program while waiting for communications activity. 10 OPEN "COM1:300,N,8,1" AS 1 20 COM(1) ON 30 ON COM(1 1 GOSUB 1000

1000 "Communication Subroutine Begin5 Here

io50 IF EOF(1) THEN RETURN Line 10 opens a file for Communications Channel 1 and allocates Buffer 1. Line 30 causes BASIC to perform the subroutine begin- ning at Line 1000 as soon as there is activity on the communi- cations channel. When all the communications data has been processed, Line 1050 returns to the main program.

151 Chmter 10 I BASIC Keywords

Statement

ERASE array[,array,. ..I

Erases one or more arrays from memory. This lets you either redimension arrays or use their previously allocated space in memory for other purposes. If one of the parameters of ERASE is a variable name that is not used in the program, an “Illegal function call” occurs. Example 458 ERASE C,F 468 DIM F(99) Line 450 erases arrays C and F. Line 460 redimensions array F.

152 Chapter 10 I BASIC Keywords

ERDEV Advanced Function

ERDEV

Returns the value of a device error within MS-DOS as set by the Interrupt 24 handler. The lower 8 bits of ERDEV contain the In- terrupt 24 error code. For more information on device drivers and errors, see the Pro- grammer’s Reference manual for your computer. It is available at your Radio Shack Computer Store. See also ERDEV$.

153 Chapter 10 I BASIC Keywords

ERDEV$ Advanced Function

ERDEV$

Returns the name of the device (as set by the Interrupt 24 han- dler) when a device error occurs. If the error occurred on a character device, ERDEV$ returns the 8-byte character device name. If the error does not occur on a character device, ERDEV$ re- turns the 2-character block device name. For more information on device drivers and errors, see the Pro- grammer’s Reference manual for your computer. It is available at your Radio Shack Computer Store. See also ERDEV.

154 Chapter 10 I BASIC Ke-ywords

ERL Statement ERL

Returns the number of the line in which an error has occurred. This function is primarily used inside an error-handling routine. If no error has occurred, ERL returns a 0. If a statement entered at BASIC’s prompt causes the error, ERL returns line number 65535 (the largest number that can be represented in 2 bytes).

Examples PRINT ERL prints the line number of the error.

E = ERL stores the error’s line number in variable E.

Sample Program See ERROR.

155 Chapter 10 I BASIC Keywords

Statement

ERR

Returns the error code if an error has occurred. ERR is only meaningful inside an error-handling routine ac- cessed by ON ERROR GOTO. See Chapter 12 for a list of error codes.

Example IF ERR = 7 THEN 1000 ELSE 2000 branches to Line 1000 if the error is an “Out of memory” error (code 7); if it is any other error, control goes to Line 2000.

Sample Program See ERROR.

156 Chapter 10 I BASIC Kevwords

ERROR Statement

ERROR code

Simulates a specified error during program execution. Code is an integer expression in the range 0 to 255 specifying one of BASIC's error codes. This statement is used mainly for testing an ON ERROR GOTO routine. When the computer encounters an ERROR statement, it proceeds as if the error corresponding to that code has occurred. (Refer to Chapter 12 for a listing of error codes and their meanings.)

Example ERROR 1 causes a "NEXT without FOR" error (Code 1) when BASIC reaches this line.

Sample Program 110 ON ERROR GOTO 400 120 INPUT "WHAT IS YOUR BET"; B 130 IF B>5000 THEN ERROR 21 ELSE GOTO 420 400 IF ERR = 21 THEN PRINT "HOUSE LIMIT IS $50 0 0" 410 IF ERL = 130 THEN RESUME 500 420 S = S+B 430 GOTO 120 500 PRINT "THE TOTAL AMOUNT OF YOUR BET 1S";S 510 END This program receives and totals bets until one of them exceeds the house limit.

157 Chapter 10 1 BASIC Keywords

EXP Function

EXP(number)

Returns the natural exponent of number, that is, e (base of natu- ral logarithms) to the power of number. Number must be less than or equal to 88.02968 This function is the inverse of the LOG function; therefore, num- ber = EXP(LOG(number)). BASIC always returns the result as a single precision number unless you specified the /D switch when starting up BASIC.

Example PRINT EXPC-2) prints the exponential value .1353353.

Sample Program 31 0 INPUT "NUMBER"; N 320 PRINT "E RCIISED TO THE"N"P0WER IS" EXPCN)

158 Chapter 10 I BASIC Keywords

FIELD Statement

FIELD buffer, length AS variable[,length AS variable, ...I

Divides a direct access buffer into fields so that you can send data from memory to disk and disk to memory. Each field is identified by variable and is the length you specify. Buffer is the number assigned to the file when you opened it. Variable must be a string variable. Length is an integer in the range 1 to 255 representing the length of that field. The sum of all field lengths are equal to the record length assigned when you opened the file. An OPEN statement assigning the buffer number must precede the FIELD statement. FIELD must precede GET and PUT. You may use the FIELD statement any number of times to re- field a file buffer. Fielding a buffer does not clear the buffer’s con- tents; it only alters the way the buffer is accessed. You may ac- cess the same disk file any number of ways simply by re-fielding it. Note: All data-both strings and numbers-must be placed into the buffer in string form. There are three pairs of functions (MKI$/CVI, MKS$ICVS, and MKD$/CVD) for converting numbers to strings and strings to numbers. See also Chapter 7, “Disk Files,” OPEN, CLOSE, PUT, GET, LSET, and RSET.

159 Chapter 10 I BASIC Keywords

Examples FIELD 3, 128 AS A$, 128 AS BS BASIC assigns 128-byte fields to the variables A$ and B$. If you now print A$ or B$, you can see the contents of the field. Of course, this value would be meaningless unless you previously have used GET to read a 256-byte record from disk. FIELD 3, 16 AS NM$, 25 AS ADS, 10 AS CY$, 2 AS ST$, 7 AS ZP$ BASIC assigns the first 16 bytes of Buffer 3 to field NM$; the next 25 bytes to AD$; the next 10 to CY$; the next 2 to ST$; and the next 7 to ZP$.

160 Chapter 10 I BASIC Keywords

FILES Statement

FILES [pathname]

Displays the names of the files and directories on a disk. Pathname is a standard file specification as described in Chapter 1. If you specify pathname, BASIC lists all files which match that pathname. If you omit pathname, BASIC lists all files and direc- tories in the current directory on the current drive. Pathname may contain question marks and asterisks as wild cards. See the section on wild cards in Chapter 1 for more information. If you specify a drive as part of pathname, then BASIC lists all files that match the specified pathname on that drive. If you omit the filename when specifying pathname, BASIC lists all files and directories in the specified directory. If you omit the path in pathname, FILES looks for the file in the current directory.

161 Chapter 10 I BASIC Keywords

Examples F I LE5 lists all files and directories in the current directory on the cur- rent drive. FILES "\BOOKS\" lists all files in the directory BOOKS. F I LE5 "* . bas" lists all files in the current directory on the current drive with the extension .bas. FILES "pay?????.ba5" lists all files beginning with pay followed by any other five or fewer characters, in the current directory on the current drive, with the extension .bas.

162 Chawter 10 I BASIC Kevwords

FIX Function

FIX(num ber)

Returns the truncated integer of number. Unlike CINT, FIX does not round the fractional portion of num- ber when making it an integer. Instead, FIX simply strips the fractional portion from number so that the resultant value is a whole number. The result is the same precision as the argument (except for the fractional portion). Unlike INT, FIX does not return the next lower number for a negative number. FIX is the same as: SGN(number)*INT(ABS(number)). See also CINT and INT, which also return integer values.

Examples PRINT FIXC2.6) prints 2. PRINT FIX(-2.6) prints -2.

163 Chapter 10 I BASIC Keywords

FOR/NEXT Statement

FOR variable = initial value TO final value [STEP increment] NEXT [variable]

Establishes a program loop that allows a series of program state- ments to be executed a specified number of times. Variabb must be either integer or single precision. Each FOR/ NEXT loop must have a unique variable. Increment is the number BASIC adds to the initial value each time the loop is executed. If you omit increment, BASIC incre- ments by 1. If increment is a negative value, BASIC decreases the initial value each time through the loop. In this case, the fi- nal value must be less than the initial value. BASIC executes the program lines following the FOR statement until it encounters a NEXT. At this point, it increases initial value by the STEP increment. If initial value is less than or equal to final value, BASIC branches back to the line after FOR and repeats the process. When initial value is greater than final value, the loop is completed, and BASIC continues with the state- ment after NEXT. Note: BASIC skips the body of the loop if initial value is greater than final value when increment is positive or if final value is greater than initial value when in- crement is negative.

164 Chapter 10 I BASIC Keywords

Sample Program BASIC always sets the final value for the loop variable before setting the initial value. For example: 820 I=5 830 FOR I = 1 TO I + 5 840 PRINT I; 850 NEXT executes the loop 10 times, which prints: 12345678910

Nested Loops FORiNEXT loops may be nested; that is, a FOR/NEXT loop may be placed within the context of another FOR/NEXT loop. The NEXT statement for the inside loop must appear before the NEXT for the outside loop. If nested loops have the same end point, a single NEXT statement may be used for all of them.

Sample Program 880 FOR I = 1 TO 3 890 PRINT "OUTER LOOP" 900 FOR J = 1 TO 2 910 PRINT " INNER LOOP" 920 NEXT J 930 NEXT I This program performs 3 outer loops and 2 inner loops within each of the outer loops. BASIC prints the following: OUTER LOOP INNER LOOP INNER LOOP OUTER LOOP INNER LOOP INNER LOOP OUTER LOOP INNER LOOP INNER LOOP

165 Chapter 10 I BASIC Keywords

By listing the counter variable, you can use the NEXT state- ment to close nested loops. (Be sure not to type the variables out of order.) For example, delete Line 920 and change 930 to: 930 NEXT J, I If you omit the variables in nested loops, BASIC matches the most recent FOR statement.

166 Chapter 10 I BASIC Keywords

FRE Function

F RE (dummy arg u mnt)

Returns the number of bytes in memory not being used by BASIC. Dummy argument can be any string or numeric constant or vari- able. If you specify a numeric argument, BASIC returns the amount of memory available. If you specify a string argument, BASIC compresses the data before returning the amount of memory available. This frees unused memory that was once used for strings. BASIC automatically compresses data if it runs out of work- space. This may take a few seconds. Examples PRINT FRE(44) prints the amount of memory left.

167 Chapter 10 I BASIC Keywords

GET Statement

GET [#lbuffr[,recordl

Reads a record from a direct access disk file and places it in the specified buffer. Buffer is the number assigned to the file when you opened it. The number sign is optional. It is provided for compatibility with other . Record is an integer in the range 0 to 16,777,215 that specifies which record number you want to access. If you omit record, BASIC reads the next sequential record (after the last GET). When BASIC encounters GET, it reads the record number from the file and places it into the buffer. The actual number of bytes read equals the record length set when the file is opened. Examples GET 1 reads the next record into Buffer 1. GET 1 ,25 reads Record 25 into Buffer 1.

168 Chapter 10 1 BASIC Keywords

GET/Communic a t ions Statement

GET [#I buffer,number

Transfers data from the communications line to the communica- tions buffer. Buffer must be the same buffer assigned to the file when it was opened. The number sign (#) is optional. It is provided for com- patibility with other BASICs. Number is the number of bytes to transfer. Number cannot ex- ceed the value used in the LEN option of the OPEN COM statement.

Note: Because of the low performance associated with telephone line communications, we recommend that you not use GET and PUT statements in such appli- cations. Instead, use the other disk 110 statements. Sample Program 10 OPEN "CUM1 :" AS 1 20 FIELD 1, 8 AS A$ 30 OPEN "R" ,2, "F ILE", 8 40 FIELD 2, 8 AS E$ 501=1 60 GET 1 ,8 70 PRINT "COMMUNICATIONS BUFFER CAS) =";A$ 80 LSET E$=&$ 90 PRINT "NOW FILE BUFFER "a" THEN GOT0 60 130 CLOSE This program gets data from Communications Channel 1 and places it in the communications buffer.

169 Chapter 10 I BASIC Ke-ywords

~ ~

GET/Graphics Statement

Transfers points from an area on the display to an array. (x1,yl)specifies the coordinates where the image begins. (x2,y2) specifies the coordinates where the image ends. x is the horizontal coordinate and y is the vertical coordinate. The ranges for the coordinates depend on the screen mode. See Chapter 8, “Displaying Color and Graphics,” for more information. Array is a numeric array to hold the image. It must be dimen- sioned large enough to hold the entire image. To ensure that the array is large enough to hold the image, use the following formula: 4 + (INT((F, * b + 7)/8) * u) where: h is the length of the horizontal side of the image. b the number of bits per point (2 in Screen Modes 1, 4, and 6; 1 in Screen Mode 2; and 4 in Screen Modes 3 and 5). u is the length of the vertical side of the image. For example, to store an image that is 10 by 12 in Screen Mode 1, type: 4 + (INT((10 * 2 + 7)/8) * 12) = 40 The array must store 40 bytes. The number of bytes per element of an array are 2 for integer, 4 for single precision, and 6 for dou- ble precision.

170 Chapter 10 I BASIC Ke-ywords

For this example, you need an integer array with 20 elements, a single precision array with 10 elements, or a double precision ar- ray with 7 elements. The information from the display is stored in the array as: Element 0 the x dimension of the image Element 1 the y dimension of the image The remaining elements of the array store the data bits of the image. Numeric data is stored low byte first and then high byte, but the data is transferred high byte first and then low byte. You use the GETiGraphics and PUTiGraphics statements to- gether for animation and high-speed object motion in the graph- ics modes. See also PUTiGraphics statement.

Note: GET and PUT work faster in all resolutions if:

xIMOD(8/bitsper point) = 0 (See Chapter 5 for an explanation of MOD.) Sample Program 10 DIM A(50,50) 20 SCREEN 1 30 CIRCLE (30,30),20 40 PAINT (30,301 50 GET (10,0)-(50,50),A 60 PUT (200,1001,A 70 END Line 10 sets up an array for storage. Line 20 selects the screen mode. Line 30 draws a circle, and Line 40 fills in the circle. Line 50 gets the circle, and stores it in Array A(). Line 60 retrieves the circle, and puts it on the screen in a new location.

171 Chapter 10 I BASIC Keywords

GOSUB Statement

GOSUB line

Branches to the subroutine beginning at the specified line num- ber. Every subroutine must end with a RETURN. You can call a sub- routine as many times as you want. When BASIC encounters a RETURN statement in the subroutine, it returns to the state- ment that follows the GOSUB. GOSUB is similar to GOT0 in that it may be preceded by a test stat ement . Example GOSUB 1000 branches to the subroutine at Line 1000.

Sample Program 260 GOSUB 280 270 PRINT "BACK FROM SUBROUTINE": END 280 PRINT "EXECUTING THE SUBROUTINE" 290 RETURN transfers control from Line 260 to the subroutine beginning at Line 280. Line 290 instructs the computer to return to the statement immediately following GOSUB.

172 Chapter 10 I BASIC Keywords

GOTO Statement

GOTO line

Branches to the specified line. When used alone, GOTO results in an unconditional branch. However, test statements, such as IFITHEN, may precede the GOTO to effect a conditional branch. Note that the GOTO is op- tional in IFiTHEN statements. For example: IF X=O THEN 360 ELSE 200 BASIC branches to Line 360 if X equals 0. If not, BASIC branches to Line 200 You can use GOTO in the command mode as an alternative to RUN. This lets you pass values assigned as a command to vari- ables used in the program.

Example GOTO 100 BASIC transfers control to Line 100.

Sample Program 10 READ R 20 IF R = 13 THEN 80 30 PR I NT "R =" ; R 40 A=3.1 4*RA2 50 PRINT "AREA =";A 60 GOTO 10 70 DATA 5,7,12, 13 80 END Line 10 reads each of the data items in Line 70; Line 60 returns program control to Line 10. This enables BASIC to calculate the area for each of the data items until it reaches item 13.

173 Chapter 10 I BASIC Keywords

HEX$ Function

HEX$(nurnber)

Calculates the hexadecimal value of number. HEX$ returns a string that represents the hexadecimal value of number. Since the value returned is like any other string, you cannot use it in a numeric expression. You cannot add hex strings; however, you can concatenate them.

Examples PRINT HEX$<30), HEX$<50), HEXtC90) prints the following strings lE, 32, and 5A. Y$ = HEX$

174 Chapter 10 I BASIC Keywords

IF/THEN/E LSE Statement

IF expression THEN statemnt(s)[ELSE statemnt(s)]

Tests a conditional expression and makes a decision regarding program flow. Expresswn is any numeric or string expression, usually making logical or relational comparisons. Statement can be 1 or more valid BASIC statements. If there is more than 1 statement, they must be separated by colons. You can also specify a line number for BASIC to branch as a statement . If expression is true, BASIC executes the THEN statement. If expresswn is false, BASIC executes the matching ELSE statement or the next program line. You can also use IFiTHEN to test the numeric value of a vari- able. If the variable contains a 0, the expression is true; other- wise, the expression is false. Examples IF X > 127 THEN PRINT "OUT OF RANGE" : END passes control to PRINT and, then to END if X is greater than 127. If X is not greater than 127, BASIC executes the next line in the program, skipping the PRINT and END statements.

IF A < B THEN PRINT "A < E" ELSE PRINT "E <= A" tests the first expression. If it is true, BASIC prints A < B. Otherwise, BASIC jumps to the ELSE statement and prints B <= A.

175 Chapter 10 I BASIC Ke.ywords

IF X > 0 AND Y <> 0 THEN Y = X + 180 assigns the value X + 180 to Y if both exm-essions are true. Otherwise, BASIC executes the next program- line, skipping the THEN clause.

IF A$ = "YES" THEN 210 ELSE IF A$ = "NO" THEN 400 ELSE 370 branches to Line 210 if A$ is YES. If not, BASIC skips to the first ELSE, which introduces a new test. If A$ is NO, then BASIC branches to Line 400. If A$ is any value besides NO or YES, BASIC branches to Line 370. Sample Program IFiTHENiELSE statements may be nested. However, you must take care to match up the IFs and ELSEs. (If the statement does not contain the same number of ELSEs and IFs, each ELSE is matched with the closest unmatched IF.) 1040 INPUT "ENTER TWO NUMBERS"; A, B 1050 IF A <= B THEN IF A < B THEN PRINT A; ELSE PRINT " NEITHER"; ELSE PRINT E; 1060 PRINT " IS SMALLER THAN THE OTHER" This program prints the relationship between the 2 numbers entered.

176 Chapter 10 I BASIC Keywords

INKEY$ Function INKEY$

Reads a character in the keyboard buffer, and returns a 0-, 1-,or 2- byte string. INKEY$ does not echo the character to the display.

0 A 0-byte (null) string indicates that no key is pressed.

0 A 1-byte string is an actual character read from the keyboard.

0 A 2-byte string indicates that the key pressed is one of the special keys that has an extended code. The first byte is hex 00. See Ap- pendices B and D for a complete list of extended codes. INKEY$ is invariably put inside some sort of loop. If not, pro- gram execution passes through the line containing INKEY$ be- fore you can press a key. The [CTRLI[m! and IHOLD] keys are not passed to INKEY$. Also [ALT][CTRLI[], which does a system reset, is not passed to INKEY$. Note: If your program contains an INKEY$ and you press a function key, BASIC returns 1 character of the key assignment at a time. For example, suppose this statement is executed: A$ = INKEYF Now suppose you press [, which initially has the value LIST. The first time the statement is executed A$ equals L, the second time A$ equals I, and so on. Keep this in mind when writing a BASIC routine to trap for a certain key. Your routine may not perform as expected if you accidently press a function key. You can assign the result of INKEY$ to a string variable and test the length of the string to determine whether a 0-, 1-, or 2- character string is returned by INKEY$. Example: 10 A$=INKEY$: IF A$="" THEN 10 20 IF LEN(A$)>l THEN PRINT ASC(MID(A$,l,I)), ASC(MID$(A$,2,1)) ELSE PRINT ASCCA$) 30 GOT0 10 Ex ample 10 A$ = INKEYS

20 IF A$ = "I' THEN 10 causes the program to wait for you to press a key.

177 Chapter 10 I BASIC Ke.ywords

INP Function

INP(port)

Returns the byte read from port. Port may be any integer from 0 to 65535. INP is the complementary function of the OUT statement.

Example 100 A=INP(255) returns the byte read from port 255 into variable A.

178 Chapter 10 I BASIC Keywords

INPUT Statement

INPUT[;] [‘~prompt”;]uariabl[,u~rzabl,...I

Accepts data from the keyboard and inputs it into 1 or more variables. When BASIC encounters this statement, it stops exe- cution and displays a question mark. This means that the pro- gram is waiting for you to type something. Prompt is a string constant that BASIC displays before display- ing the question mark prompt. Prompt must be enclosed in quo- tation marks, and follow the keyword INPUT. If, instead of a semicolon, you type a comma after prompt, BASIC suppresses the question mark when printing the prompt. Variable may be 1 or more string or numeric variables to receive the input. If you specify more than 1 variable, separate them by commas. If INPUT is immediately followed by a semicolon (;I, BASIC does not echo the [ENTER] key when you press it as part of a response. When typing multiple pieces of data on 1 line, separate the data items with a comma. The number of data items you supply must be the same as the number of variables you specify. Responding to INPUT with too many items or with the wrong type of value (including numeric type) causes BASIC to print the message “?Redo from start.” No values are assigned until you provide an acceptable response.

179 Chapter 10 I BASIC Kevwords

Examples INPUT Y% when BASIC reaches this line, you must type any number and press JENTERI before the program can continue. INPUT SENTENCES when BASIC reaches this line, you must type in a string. The string does not have to be enclosed in quotation marks unless it contains a comma, a colon, or a leading blank. INPUT "ENTER YOUR NAME, AGE"; N$, A prints the prompt string on the screen, which helps the user en- ter the right kind of data.

Sample Program 50 INPUT "HOW MUCH DO YOU WEIGH"; X 60 PRINT "ON MARS YOU WOULD WEIGH ABOUT" CINTCX * .38) "POUNDS."

180 Chawter 10 I BASIC Kevioords

INPUT# Statement

INPUT# buffer, variable[,variable...I

Accepts data from a sequential device or file and stores it in a program variable. Buffer is the number assigned to the file when you opened it. Variable is any string or numeric variable to contain the infor mat ion. The sequential file may be a disk file, a data stream from a com- munications device, or the keyboard device. With INPUT#, data is input sequentially. That is, when the file is opened, a pointer is set to the beginning of the file. The pointer advances each time data is input. To start reading from the beginning of the file again, you must close the file buffer and reopen it. INPUT# does not care how you place the data in the file- whether you use a single PRINT# statement or 10 different PRINT# statements. INPUT# looks only for the position of the terminating characters and the end-of-file (EOF) marker. When inputting data into a variable, BASIC ignores leading blanks. When the first nonblank character is encountered, BASIC assumes it has encountered the beginning of the data item.

181 Chapter 10 I BASIC Ke-ywords

The data item ends when BASIC encounters a terminating char- acter or when a terminating condition occurs. The terminating characters vary, depending on whether BASIC is inputting to a numeric or a string variable: Numeric: BASIC ends input when it encounters a carriage return or a comma. String: BASIC ends input when it encounters a carriage re- turn or a comma, unless the first character is a quotation mark( " ). If the first character is a quotation mark, BASIC ends input when it encounters a second quotation mark. Thus, a quoted string may not contain a quotation mark as a character.

Examples INPUT#l, A,B sequentially inputs 2 numeric data items from the file opened to Buffer 1 and places them in A and B. INPUT#4, A$, E$, C$ sequentially inputs 3 string data items from the file opened to Buffer 4 and places them in A$, B$, and C$.

182 Chapter 10 I BASIC Ke.ywords

INPUT$ Statement

INPUT$( nu m ber [, [ # ] buffer])

Accepts a string of characters from either the keyboard or a se- quential access file. Number is the number of characters to be input. It must be a value in the range 1 to 255. Buffer is a buffer that accesses a sequential input file. If you in- clude buffer, BASIC inputs the string from sequential access file. If you omit buffer, BASIC inputs the string from the keyboard. The number sign (#) is optional. It is provided for compatibility with other BASICs. When inputting the string from the keyboard, BASIC waits until the user enters the number of characters specified by number. You do not need to press [m]to signify end-of-line. The charac- ter(s) you type are not displayed on the screen. Any character, except F][EiEK],is accepted for input. When inputting from a sequential file, BASIC inputs the num- ber of bytes specified by number from the file assigned to buffer. Examples

A$ = INPUT$(S) assigns a string of 5 keyboard characters to A$. Program execu- tion halts until 5 characters are typed at the keyboard.

A$ = INPUT$C11,3) assigns a string of 11 characters to A$. The characters are read from the file associated with Buffer 3.

183 Chapter 10 I BASIC Keywords

Sample Programs This program shows how you can use INPUT$ to have an opera- tor input a password for accessing a protected file. By using IN- PUT$, you can type in the password without anyone seeing it on the video display. To see the full file specification, run the pro- gram. When the BASIC prompt returns, type PRINT F$. 110 LINE INPUT "TYPE IN THE FILENAME.EXT"; F$ 120 PRINT "TYPE IN THE PASSWORD -- MUST TYPE 8 CHARACTERS : " ; 130 P$ = INPUT$<8) 140 F$ = F$ + 'I." + P$ 150 PRINT "YOUR FILENAME IS"; FS In the program below, Line 100 opens a sequential input disk file (which we assume has been previously created). Line 200 re- trieves a string of 70 characters from the file and stores them in T$. Line 300 closes the file. 100 OPEN "I", 2, "test.dat" 200 T$ = INPUT$<70,2) 300 CLOSE

184 Chapter 10 I BASIC Keywords

INSTR Function

Searches for the first occurrence of string2 in stringl and re- turns the position at which the match is found. Number specifies the position in stringl to begin searching for string2. Number must be an integer in the range 1 to 255. If you omit number, INSTR starts searching at the first character in stringl . If BASIC finds string2 in stringl, it returns the starting position of the match; otherwise, it returns zero. If the entire substring is not contained in the search string, BASIC returns a zero.

Examples

Suppose A$ = “LINCOLN” Statement BASIC returns INSTR(A$, “INC”) 2 INSTR(A$, “12”) 0 INSTR(A$, “LINCOLNABRAHAM”) 0

For a slightly different use of INSTR, try: 10 X=INSTR (3, “1232123”, “12”) 20 PRINT X which prints 5, because the search started at the third character.

185 Chapter 10 I BASIC Ke-ywords

Sample Program The program below uses INSTR to search through the addresses contained in the program's DATA statements. It counts the num- ber of addresses with a specified county zip code (761--) and re- turns that number. The zip code is preceded by an asterisk to distinguish it from the other numeric data found in the address. 360 RESTORE 370 COUNTER = 0 390 READ ADDRESS$ 395 IF ADDRESS$ = "SEND" THEN 410 400 IF INSTRCADDRESSS, "*761") <> 0 THEN COUNTER = COUNTER + 1 ELSE 390 405 GOT0 390 410 PRINT "NUMBER OF TARRANT COUNTY, TX ADDRESSES IS" COUNTER : END 420 DATA "5950 GORHAM DRIVE, BURLESON, TX *761 48" 430 DATA "71 FIRSTFIELD ROAD, GAITHERSBURG, MD * 2 0 760 'I 440 DFlTA "1000 TWO TANDY CENTER, FORT WORTH, TX *761 02" 450 DATA "16633 SOUTH CENTRAL EXPRESSWAY, RICHARDSON, TX ~75080" 460 DATA ."$END"

186 Chapter 10 I BASIC Keywords

INT Function

INT(num ber)

Converts number to the largest integer that is less than or equal to number. Number is not limited to the integer range - 32768 to 32767 The result has the same precision as number (except for the frac- tional portion). Unlike CINT, INT does not round positive numbers. It does, however, round negative numbers.

Examples PRINT INTC79.89) prints 79. PRINT INT (-12.11) prints -13.

187 Chapter 10 I BASIC Keywords

IOCTL Advanced Statement

IOCTL [#lbuffr,string

Sends a control data string to a device driver. Control data can be sent to a drive only after it has been opened. Buffer is the number assigned to the driver when you opened it. The number sign (#) is optional. It is provided for compatibility with other BASICs. String is a string expression containing a series of commands called "control data." The commands are generally 2 to 3 charac- ters long and may be followed by an alphanumeric argument. The commands are separated by semicolons (;). String may be a maximum of 255 bytes. For more information on device drivers, see the Programmer's Reference manual for your computer. It is available at your Radio Shack Computer Store.

Example If you write your own driver to replace PRN to set the page length, the IOCTL command may be: PLn where n is the new page length. To open the new PRN driver and set the page length at 56 lines per page, use the following statements:

10 OPEN "PRN" FOR OUTPUT a5 1 20 IOCTL 1 ,"PL56"

188 Chapter 10 I BASIC Keywords

IOCTL$ Advanced Function

IOCTL$([#lbuf,r)

Returns the control data string from a device driver that you have opened previously. Buffer is the number assigned to the driver when you opened it. The number sign (#) is optional. It is provided for compatibility with other BASICs. You can use the IOCTL$ function to confirm that a IOCTL statement succeeded (or failed). You can also use IOCTL$ to get information from the device. For more information on device drivers, see the Programmer's Reference manual for your computer. It is available at your Radio Shack Computer Store. Example 10 OPEN "\DEV\PRN" FIS 1 20 IF IOCTL$CI) = "NR" THEN PRINT "PRINTER NOT REFIDY"

189 Chapter 10 I BASIC Keywords

KEY/Set/Display Statement

KEY number,string KEY ON KEY OFF KEY LIST

KEY number,string Assigns or displays function key values. Number is an integer in the range 1 to 12 that indicates the function key being defined (m-[I. String is the string expression assigned to the key and may con- tain a maximum of 15 characters. You can program the function keys on your computer to generate a specific string of characters. When you press the key, BASIC displays the string on the screen just as if you had typed every character. Initially, the function keys have these values: F1 LIST F7 TRONm F2 RUN= F8 TROFF- F3 LOAD“ F9 KEY F4 SAVE“ F1O SCREEN 0,0,0 [ENTERI F5 CONT- F11 none F6 ,“LPTl:”m F12 none Function keys 11 and 12 do not have initial values. You can use the KEY statement to define these keys. You also can use the KEY statement to redefine the other function keys so that BASIC displays the strings you use most often. You can remove the string from a function key by assigning it a string length of zero (“ ”). For example:

KEY 1 , “‘I Key no longer has a string assigned to it. Moreover, assign- ing a null string (length zero) to a function key disables it as a soft key. If the soft key is disabled, INKEY$ returns a 2-byte string. See Appendix D for more information.

190 Chapter 10 I BASIC Keywords

KEY ON KEY ON displays the function key assignment values on Line 25 of the screen. If the screen width is 40, the screen shows 5 func- tion key assignments at a time. If the width is 80, the screen shows 10 assignments at a time. Press (CTRL] p) to display the next screen and to erase the display after the last assignments are shown.

KEY OFF KEY OFF erases the soft key assignments from Line 25. The as- signments are still active, but the screen does not display them. BASIC reserves Line 25 for the function key display. Even if the display is turned off, BASIC does not display program lines on Line 25. Note: Instead of using KEY ON and KEY OFF, you can use [m][TJ as a toggle switch to turn the key as- signment display on and off, as well as to cause it to advance to the next screen. KEY LIST KEY LIST displays all 15 characters of all 12 soft key assign- ments on the screen. Note: If your program contains an INKEY$ and you press a function key, BASIC returns 1 character of the key assignment at a time. For example, suppose this stat ement is executed:

A$ = INKEY$ Now suppose you press I,which initially has the value LIST. The first time the statement is executed A$ equals L, the second time A$ equals I, and so on. Keep this in mind when writing a BASIC routine to trap for a certain key. Your routine may not perform as expected if you accidentally press a function key.

191 Chapter 10 I BASIC Keywords

KEY/Trap Statement

KEY(number) action

Turns on, turns off, or temporarily halts key trapping for a spec- ified key. Action may be any of the following: ON enables key trapping OFF disables key trapping STOP temporarily suspends key trapping Number may be a number in the range 1 to 20, indicating the number of the key to trap. Function keys use their corresponding function key number (1-10). The cursor direction key trap num- bers are: 11 12 13 14 User-defined keys are 15-20. Use the following syntax to define your own user keys: KEY number, CHR$(key) + CHR$(scan) Key is one of or a combination of the following: &H40 [CAPSJ lock key &H20 (NUMLOCK] key &H08 (ALT) key &H04 [CTRLJ key &H02 Left key &H01 Right key Scan is the scan code for a physical key on the keyboard. See the appendices for a list of scan codes. Notes: Trapped keys do not go into the keyboard buffer.

0 Defining a function key or a cursor-direction key has no effect. BASIC considers them pre-defined.

192 Chapter 10 I BASIC Keywords

0 You can trap any key, including (CTRL] @J, [CTRLIIBREAK), and [CTRL] [DELETE) (the soft boot). This feature makes it possible to prevent BASIC application users from con- trol-breaking out of a program or from accidentally reset- ting the computer. You can use the KEYITrap statement in a key trapping routine with the ON KEYO GOSUB statement to detect when a specific key is pressed. The KEYO ON statement turns on key trapping for a specific key. BASIC checks after each program statement to see if the specified key has been pressed. If so, BASIC transfers program control to the line number specified in the ON KEY() GOSUB statement. For example: KEY(3) ON ON KEY(3) GOSUB 1000 BASIC turns on a trap for m. BASIC continues to execute the other program statements, checking after each statement to see if iF3] has been pressed. When IF3] is pressed, BASIC branches to the subroutine beginning at Line 1000. KEYO STOP temporarily halts trapping for the specified key. If the specified key is pressed, BASIC does not transfer program control to the ON KEYO GOSUB until you turn on key trapping again with a KEY() ON statement. BASIC remembers that the key was pressed and branches to the subroutine immediately after key trapping is turned on again. KEY() OFF turns off key trapping. BASIC does not remember that the key has been pressed when key trapping is turned on again. Note: Key trapping only occurs while BASIC is run- ning a program. See ON KEY() GOSUB for more information on key trapping.

Sample Program See ON KEY() GOSUB.

193 Chapter 10 I BASIC Keywords

KILL Statement

KILL pathname

Kills (deletes) pathnume from disk. Pathname is a standard file specification as described in Chapter 1. You may delete any type of disk file. However, if the file is cur- rently open, a "File already open" error occurs. You must close the file before deleting it.

Example

K I LL "f i 1 e. ba 3" deletes file.bas if it exists in the current directory. KILL "A:\REPORT\data" deletes data from the directory REPORT in Drive A.

194 Chapter 10 I BASIC Keywords

LCOPY Statement

LCOPY

Copies all text data on the screen to the printer

Sample Program 550 FOR 1=1 TO 24 560 PRINT STRING$(79,33) 570 NEXT I 580 LCOPY This program segment prints exclamation points on the screen, and dumps them to the printer.

195 Chapter 10 I BASIC Keywords

LEFT$ Function

LEFT$(string,num ber)

Returns the specified number of characters from the left portion of string. Number must be an integer in the range 1 to 255. If number is equal to or greater than the length of the string, BASIC returns the entire string.

Examples PRINT LEFTS("BATTLESHIPS", 6) prints BATTLE. PRINT LEFT$C"BIG FIERCE DOG", 28) Since BIG FIERCE DOG is fewer than 20 characters, BASIC prints the whole phrase.

Sample Program

740 A$ = "TIMOTHY" 750 E$ = LEFT$(A$, 3) 760 PRINT E$; "--THAT'S SHORT FOR "; AB When you run this program, BASIC prints: TIM--THAT'S SHORT FOR TIMOTHY Line 750 gets the 3 left characters of A$ and stores them in B$. Line 760 prints these 3 characters, a string, and the original contents of A$.

196 Chapter 10 I BASIC Keywords

LEN Function

LEN(string)

Returns the number of characters in string. Blanks are counted. Examples

X = LEN

PRINT LEN("CAMBR1DGE") + LEN<"BERKELEY") prints 17. PRINT LEN("ORLAND0, FLORIDA") prints 16.

197 Chapter 10 I BASIC Ke-ywords

LET Statement

[LET] variable = expression

Assigns the value of expression to variable. Variable is a numeric or string variable. Expression is a numeric or string constant or expression. A BASIC function can be substituted for expression. BASIC does not require assignment statements to begin with LET, but you might want to use LET to be compatible with ver- sions of BASIC that do require it.

Examples

LET A$ = "A ROSE IS A ROSE" LET E1 = 1 .23 LET X = X - 21 LET X = SQRCB) In each case, the variable on the left side of the equals sign is assigned the value of the constant, expression, or function on the right side.

Sample Program

550 P = 1001 : PRINT "P 1'' P 560 LET P = 2001: PRINT "NOW P ="P

198 Chapter 10 I BASIC Ke.ywords

LINE/Graphics Statement

Draws a line or a box on the video display. The STEP option tells BASIC that the (x,y) coordinates are rela- tive to the last point referenced. If you use STEP with the sec- ond set of coordinates, the coordinates are relative to the first set of coordinates. (x1,yl) specifies the point at which to begin the line. xl is the horizontal coordinate, and yl is the vertical coordinate. If you omit (x1,yl) BASIC begins the line at the last point referenced on the screen. (x2,yZ) specifies the point at which to end the line. x2 is the hor- izontal coordinate and y2 is the vertical coordinate. Color indicates the color of the line. See Chapter 8, “Displaying Color and Graphics” for information on coordinates and colors for the current screen mode. If you specify coordinates that are not in the range of the cur- rent viewport, BASIC displays only that portion of the line that is within the viewport. With the B option, BASIC draws a box. The points that you specify are opposite corners. If you specify both the B and F options, BASIC draws a box and fills the box in with color. Style lets you select the line-style used when drawing normal lines and unfilled boxes. Style is a 16-bit integer. Each bit repre- sents a point in the line. If the bit equals 1, then the point is drawn. If the bit equals zero, then the point is not drawn. A zero bit does not erase a previously drawn point; therefore, you may want to draw a background line first to have a known back- ground. The style pattern is repeated as necessary, to complete the line drawing.

199 Chapter 10 I BASIC Keywords

Here are some sample styles showing the bit representation, the line drawn, and their hex equivalents: 0 1 0 1 0 1 0 10 1 0 1 0 1 0 1 equals &H5555 -----__ - is drawn

1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 lequals&HDBGD __ __ -- __ -_ - is drawn

Examples You can try these examples in Screen Modes 1 to 6. The color, size, and position of the image on the display vary, depending on the current screen mode. LINE -(319, 199) draws a line from the last point referenced to point 319,199 in the default color. This is the simplest form of the LINE state- ment. Note that when you omit the beginning points you must still include the hyphen. LINE (0,0)-(319,199) draws a diagonal line on the display in the default color. LINE C 0,100 )-(319,100 1 ,l draws a horizontal line across the display in Color 1. LINE (0,0)-<100,100), ,E draws a box in the upper left corner of the display. LINE (0,0)-(200,200),1 ,BF draws a box on the display and fills it in with Color 1. LINE (0,0)-(200,200),1,B, &H5555 draws a box outlined by a dashed line.

200 Chapter~. 10 I BASIC Keywords

Sample Programs 10 CLS 20 LINE -(RND*319,RND*199),RND+4 30 GO TO 20 In Screen Modes 1 to 6, Lines 10-30 create a loop that draws random lines on the video display. 40 FOR X=O TO 319 50 LINE (X,B)-(X,199),X FlND 1 60 NEXT In Screen Modes 1 to 6, Lines 40-60 draw an alternating pat- tern, turning on and off the line. 10 CLS 20 LINE -(RND*639,RND*199),RND*2,BF 30 GO TO 20 This program draws a random filled box in Screen Modes 1 to 6.

201 Chapter 10 I BASIC Keywords

LINE INPUT Statement

LINE INPUT[;]["prompt";]string variable

Accepts an entire line (a maximum of 255 characters) from the keyboard. LINE INPUT is a convenient way to input string data without accidental entry of delimiters (commas, quotation marks, etc.). Prompt is a string constant enclosed in quotation marks that BASIC prints before waiting for input. String variable is the variable to receive the input. The only way to terminate the string input is to press I. However, if LINE INPUT is immediately followed by a semicolon, pressing [ENTER] does not echo a carriage return to the display. Note: You must place a space between LINE and INPUT. LINE INPUT is similar to INPUT, except:

0 BASIC does not display a ? when waiting for input. 0 Only 1 variable can be assigned at a time. 0 Commas and quotation marks can be entered in the string input. 0 Leading blanks are not ignored.

Examples LINE INPUT A$ waits for input to A$ without displaying a prompt.

LINE INPUT "LAST NAME, FIRST NAME? 'I; N$ displays the message and waits for input.

202 Chapter 10 I BASIC Ke.ywords

LINE INPUT# Statement

LINE INPUT# buffer, variable

Accepts an entire line of data from a sequential file to a string variable. Buffer is the number assigned to the file when you opened it. This statement is useful when you want to read an ASCII format BASIC program file as data or when you want to read in data without following the usual restrictions regarding leading char- acters and terminators. LINE INPUT# reads everything from the first character up to:

0 the end-of-file the 255th data character 0 a carriage return Other characters encountered-quotation marks, commas, lead- ing blanks-are included in the string. Note: You must place a space between LINE and INPUT#.

Example If a ASCII format program file looks like this: 10 CLEAR 500 20 OPEN "I", 1, "prog" then the statement: LINE INPUT#l, A$ can be used repeatedly to read each program line, one at a time.

203 Chapter 10 I BASIC Keywords

LIST Statement

LIST startline-endline [,deuicel

Lists a program in memory to the display. Startline specifies the first line to be listed. If you omit startline, BASIC starts with the first line in your program. Endline specifies the last line to be listed. If you omit endline, BASIC ends with the last line in your program. If you omit both startline and endline, BASIC lists the entire program. Device may be either SCRN: (screen) or LPT1: (line printer 1).If you omit deuice, the lines are listed to the screen. You can temporarily stop the listing by pressing [HOLD1. Press [HOLDJ again to continue the listing. You can substitute a period (.) for either startline or endline to indicate the current line number.

Examples LIST displays the entire program. LIST 50-85, "'sCRN:" displays lines in the range 50 to 85 on the screen. LIST .- displays the program line that you have entered or edited and all higher numbered lines on the screen. LIST -227 displays all lines up to and including 227 on the screen. LIST 227- ,"LPTl :" lists Line 227 and all higher numbered lines to the printer.

204 Chapter 10 I BASIC Ke-ywords

LLIST Statement

LLIST startline-endline

Lists program lines in memory to the printer. Startline specifies the first line to be listed. If you omit startline, BASIC starts with the first line in your program. Endline specifies the last line to be listed. If you omit endline, BASIC ends with the last line in your program. If you omit both startline and endline, BASIC lists the entire program. You can substitute a period (.) for either startline or endline to indicate the current line number. LLIST assumes an 80-character-wide printer. You may change this by using the WIDTH statement with the LPRINT option.

Examples LLIST lists the entire program to the printer. To stop this process, press (. This causes a temporary halt in the computer’s out- put to the printer. Press IHOLD] again to continue printing. LLIST 68-90 prints lines in the range 68 to 90.

205 Chapter 10 I BASIC Keywords

LOAD Statement

LOAD pathname [,Rl

Loads a BASIC program from disk into memory. Pathname is a standard file specification used to save the file to disk. The R option tells BASIC to run the program. (LOAD with the R option is equivalent to the command RUN pathname.) When you specify the R option, BASIC leaves all open files open and runs the program automatically. If you omit the R option, BASIC wipes out any resident BASIC program, clears all variables, and closes all open files. You can use either of these commands inside programs to allow program chaining (one program calling another). If you attempt to LOAD a non-BASIC file, a "Direct statement in file" error occurs.

Example LOAD "A: progl . ba5" loads progl .bas from Drive A, and then returns to the command mode. LOAD "progl .bas" loads progl .bas. Because no drive is specified, BASIC searches for progl .bas on the current drive.

206 Chapter 10 I BASIC Ke.ywords

LOC Function

LOC(buffer)

Returns the current record position within a file. Buffer is the number assigned to the file when you opened it. You use LOC to determine the current record position, that is, the number of the last record processed since you opened the file. When used with direct access files, LOC returns the record number accessed by the last GET or PUT statement. When used with sequential files, LOC returns the number of 128-byte blocks that have been read or written. Example IF LOC(1)>55 THEN END Program execution ends, if the current record position is greater than 55. Sample Program

1310 CIS = "WILLICIM WILSON" 1320 GET 1 1330 IF N$ = A$ THEN PRINT "FOUND IN RECORD" LOCCI): CLOSE: END 1340 GOT0 1320 This is a portion of a direct access program. Elsewhere the file has been opened and fielded. N$ is a field variable. If N$ matches A$, the record number in which it was found is printed.

207 Chapter 10 I BASIC Keywords

LO C/Communic ations Function

LOC (buffer)

Returns the number of characters in the input queue if that number is 255 or less. If the queue contains 256 or more characters, the LOG function returns the number 255. Since a string is limited to 255 charac- ters, this limit eliminates the need for testing string size before reading data into the queue. Buffer is the number assigned to the file when you opened it. The default size for the input queue is 256 characters, but you can change the size by using the /C: option when loading BASIC. Ex ample 10 X=LOC0 THEN A$=INPUT$(LOC(l),#I) Line 18 checks to see if there are any characters in the input queue and stores the number of characters in the variable X. Line 20 tests the value of X. If X is greater than 0, there are characters in the input queue, and Line 28 returns the charac- ters in the buffer into A$. Notice from the example that INPUT$ is preferred over LINE INPUT# or INPUT# when reading communications files. This preference is because all ASCII characters might be significant in communications. INPUT$ allows all characters to be read. The other statements do not. LINE INPUT# stops at a carriage return. INPUT# stops at a comma or a carriage return.

208 Chapter 10 I BASIC Keywords

LOCATE Statement

LOCATE [row][,[coZurnnl[, [cursor] [,[startl[,stopllll

Positions the cursor on the screen. Row is a numeric expression in the range 1 to 25 that indicates the screen row where you want to position the cursor. Column is a numeric expression that indicates the screen column where you want to position the cursor. It may be in the range 1 to 40 or 1 to 80, depending on the current screen width. Cursor indicates whether the cursor is visible or invisible. Set cursor to 1 for a visible cursor and to 0 for an invisible cursor. Start specifies the starting scan line of the cursor. There are 7 scan lines available for the cursor. Start must be an integer in the range 0 to 7, where 0 is the top line and 7 is the bottom line. Stop specifies the ending scan line of the cursor. Stop must be in the same range as start. If stop is less then start BASIC displays a split cursor. Cursor, start, and stop are only effective in Screen Mode 0.

Examples LOCATE 10,20,1 ,4 positions a half cursor on Row 10 in Column 20. LOCATE 24,l ,l ,7 positions an underline cursor in the first position of the last line.

209 Chapter 10 I BASIC Keywords

LOF Function

LOF ( buffer)

Returns the length of the file in bytes. Buffer is the number assigned to the file when you opened it.

Example Y = LOF(5) assigns the length of the file in bytes to variable Y

Sample Programs During direct access to an existing file, you often need a way to know when you have read the last valid record. LOF provides a way: 1540 OPEN "R", 1, "unknown.txt", 128 1550 FIELD 1, 128 AS A$ 1560 RCNUM% = 1 'START AT BEGINNING OF FILE 1570 RCSIZ% = 128 'SET RECORD SIZE 1580 IF RCNUM% * RCSIZ% > LOF(1) GOTO 1640 1590 'CHECK FOR END OF FILE 1600 GET 1, RCNUMX 'RECORD NUM. TO BE ACCESSED 1610 PRINT AS 1620 RCNUM% = RCNUM% + 1 'INCREMENT RECORD NUM 1630 GOTO 1580 1640 CLOSE If you attempt to GET record numbers beyond the end-of-file, BASIC gives you an error. These lines use LOF to determine where to start adding when you want to add to the end of a file:

1700 RCNUM% = (LOFC1) / RCSIZ%) + 1 1720 'HIGHEST EXISTING RECORD 1720 PUT 1, RCNUM% 'ADD NEXT RECORD

210 Chapter 10 I BASIC Ke,ywords

LOFlC ommunications Function

LOF ( buffer)

Returns the amount of free space in the input queue. Buffer is the number assigned to the file when you opened it. You can use LOF to determine when an input queue is getting full so that transmission is stopped. The default length of the communications receive buffer is 256 bytes. If you wish, you can specify a different length by using the iC: switch when loading BASIC. (See “Options for Loading BASIC” in Chapter 2.)

211 Chapter 10 I BASIC Keywords

LOG Function

LOG(number)

Returns the natural logarithm of number. Number must be greater than zero. LOG is the inverse of the EXP function. BASIC always returns the result as a single precision number.

Examples PRINT LOG(3.14159) prints the value 1.144729 Z = 10 LOG(PS/Pl) performs the indicated calculation and assigns the value to Z.

Sample Program This program demonstrates the use of LOG. It utilizes a formula taken from space communications research. 540 INPUT "DISTANCE SIGNAL MUST TRAVEL (MILES)"; D 550 INPUT "SIGNAL FREQUENCY (GIGAHERTZ)". F 560 L = 96.58 + (20 * LOGCF)) + (20 LOiCD)) 570 PRINT "SIGNAL STRENGTH LOSS IN FREE SPACE IS" L "DECIBELS."

212 Chapter 10 I BASIC Keywords

LPOS Function

LPOS(number)

Returns the logical position of the print head within the printer’s buffer. Number can be 0 or 1 to indicate LPT1:. LPOS is only useful for checking the position of the print head after a LPRINT statement that is terminated by a semicolon to suppress the automatic carriage return. The statement contain- ing LPOS is not executed until the LPRINT statement is fin- ished printing. LPOS does not necessarily give the physical position of the print head if the printed string contains the ASCII code for a carriage return. For example, if you are printing a string of 20 characters and the 10th character is the ASCII code for a carriage return, the printer advances to the next line after printing the ninth character before printing the remaining 10 characters. If the string is terminated by a semicolon to supress the automatic line feed, the physical location of the print head is at position 10, but LPOS returns a value of 21 because that is the logical location of the print head. Example You may want to use LPOS to determine whether there is enough room to continue printing more variables on the same line. 100 IF LPOS(X)>60 THEN LPRINT If the printer has printed more than 60 characters, a carriage return is sent so that the printer skips to the next line.

213 Chapter 10 I BASIC Keywords

LPRINT Statement

LPRINT [USING format;]data[,data, ...I

Prints data on the printer. LPRINT assumes a print width of 80 characters. You may change the width using the WIDTH statement with the LPRINT option. See PRINT and PRINT USING for more information on format- ting the output.

Examples LPRINT (A * 2)/3 prints the value of expression (A * 2)/3 on the printer. LPRINT TAB(S0) "TABBED 50" moves the printer carriage to tab position 50 and prints TABBED 50. (Refer to the TAB function.)

LPR I NT US I NG 'I#####.#'I; 2.17 sends the formatted value bbbb2.2 to the printer.

214 Chapter 10 I BASIC Keywords

LSET Statement

LSET field name = data

Moves data to the direct access buffer and places it in field name, in preparation for a PUT statement. Field name is a string variable defined in a FIELD statement. You must have used FIELD to set up buffer fields before using LSET. You must convert numeric values to string values before they are LSET. See MKI$, MKD$, MKS$. You use LSET to left-justify the variable in the field. If the field is larger than the variable it is receiving, the field is filled with blanks on the right. If the variable is larger than the field, char- acters are truncated on the right. The complement command to LSET is RSET. See also Chapter 7, “Files,” and OPEN, CLOSE, FIELD, GET, PUT, and RSET. Example Suppose NM$ and AD$ have been defined as field names for a direct access file buffer. NM$ has a length of 18 characters; AD$ has a length of 25 characters. The statements:

LSET NM$ = “JIM CRICKET, JR.” LSET AD$ = “2000 EAST PECAN ST.” set the data in the buffer as follows: JIMMCRICKET,JR.BBM 2000MEASTMPECANMST.MMB~BM Notice that filler blanks are placed to the right of the data strings in both cases. If we use RSET statements instead of LSET, the filler spaces are placed to the left. This is the only difference between LSET and RSET.

215 Chapter 10 I BASIC Keywords

MERGE Statement

MERGE pathname

Loads a BASIC program and merges it with the program cur- rently in memory. Pathnume is a standard file specification as described in Chapter 1. The filename is required. The file must be in ASCII format; that is, it must have been saved with the A option. Program lines in pathname are inserted into the resident pro- gram in sequential order. For example, suppose that 3 lines from pathname are numbered 75, 85, and 90, and 3 lines from the resident program are numbered 70, 80, and 90. When you use MERGE on the 2 programs, this portion of the merged program is now numbered 70, 75, 80, 85, 90. If line numbers on the new program coincide with line numbers in the resident program, the new program's lines replace the res- ident program's lines. MERGE closes all files and clears all variables. Upon completion, BASIC returns its prompt. Example Suppose you have a BASIC program on disk, prog2.M (saved in ASCII), that you want to merge with the program you have in memory: MERGE "prog2. txt" merges the 2 programs.

216 Chapter 10 I BASIC Keywords

Sample Programs MERGE provides a convenient means of putting program mod- ules together. For example, an often-used set of BASIC subrou- tines can accompany a variety of programs with this command. Suppose the following program is in memory: 80 REM MAIN PROGRAM 90 REM LINE NUMBER RESERVED FOR SUBROUTINE HOOK 100 REM PROGRAM LINE 110 REM PROGRAM LINE 120 REM PROGRAM LINE 130 END And suppose the following subroutine, sub.txt, is stored on disk in ASCII format: 90 GOSUB 1000 'SUBROUTINE HOOK 1000 REM BEGINNING OF SUBROUTINE 1010 REM SUBROUTINE LINE 1020 REM SUBROUTINE LINE 1030 REM SUBROUTINE LINE 1040 RETURN You can MERGE the subroutine with the main program with: MERGE "5ub. txt" The new program in memory is: 80 REM MAIN PROGRAM 90 GOSUB 1000 'SUBROUTINE HOOK 100 REM PROGRAM LINE 110 REM PROGRAM LINE 120 REM PROGRAM LINE 130 END 1000 REM BEGINNING OF SUBROUTINE 1010 REM SUBROUTINE LINE 1020 REM SUBROUTINE LINE 1030 REM SUBROUTINE LINE 1040 RETURN

217 Chapter 10 I BASIC Ke.ywords

MID$ Statement

MID$(oldstring,start[,length]) = newstring

Replaces a portion of oldstring with newstring. Oldstring is the variable name of the string you want to change. Start is a number specifying the position of the first character you want to change. Length is a number specifying the number of characters you want to replace. Newstring is the string to replace a portion of oldstring. The length of the resultant string is always the same as the original string. If newstring is shorter than length, the entire re- placement string is used. Examples: 10 FIB = "LINCOLN" 20 MID$CAB,3,4) = "12345": PRINT AB prints LI1234N. Replace Line 20 with:

20 MIDB

218 Chapter 10 I BASIC Ke.ywords

MID$ Function

MID$(string, start [,length]>

Returns a substring of a string. Length is the number of characters in the substring. It must be in the range 1 to 255. Start specifies the position in the string from which to get the substring. If you omit length or if there are fewer than that number of char- acters to the right of start position, BASIC returns all characters to the right of the character at the start position including that character at start. If start is greater than number of characters in string, BASIC re- turns a null string.

Examples

10 A$ = "WEATHERFORD" 20 PRINT MIDSCAS, 3, 2) prints AT

F$ = MID$

Sample Program 200 INPUT "AREA CODE AND NUMBER (NNN-NNN-NNNN)"; PH$ 210 EX$ = MID$CPH$, 5, 3) 220 PRINT "NUMBER IS IN THE " EX$ " EXCHANGE." The first 3 digits of a local phone number are sometimes called the exchange of the number. This program looks at a complete phone number (area code, exchange, last 4 digits) and picks out the exchange.

219 Chapter 10 I BASIC Ke.ywords

MKDIR Statement

MKDIR dirpath

Creates the directory specified by dirpath. Dirpath is a standard directory specification as described in Chapter 1. If you omit the drive identifier, the directory is cre- ated on the current drive. If you omit the root directory symbol (\I, the directory is created in the current directory. Examples MKDIR "A: \ACCTS\PAYABLE" creates the directory PAYABLE in the ACCTS directory on Drive A. MKDI R "\ADDRESS" creates the directory ADDRESS in the root directory on the cur- rent drive. MKDI R "NAMES" creates the directory NAMES in the current directory on the current drive.

220 Chapter 10 I BASIC Ke.ywords

MKD$, MKI$, MKS$ Function

MKD$(double precision expression) MKI$( integer expression) MKS$(single precision expression)

Converts numeric values to string values. Any numeric value that is placed in a direct file buffer with an LSET or RSET statement must be converted to a string. These 3 functions are the inverse of CVD, CVI, and CVS. The byte values that make up the number are not changed; only 1 byte, the internal data-type specifier, is changed so that numeric data can be placed in a string variable. MKD$ returns an 8-byte string; MKI$ returns a 2-byte string; and MKS$ returns a 4-byte string.

Example

LSET AVGS. = MKSS(0.123)

Sample Program

1350 OPEN "R", 1 I "te~t.dat", 14 1360 FIELD 1, 2 AS 119, 4 AS I2$, 8 AS 13s 1370 LSET IIS = MKIS(3000) 1380 LSET 12s = MKSSC3000.1) 1390 LSET 13s = MKDSC3000.00001) 1400 PUT 1, 1 1410 CLOSE 1 For a program that retrieves the data from test.dat, see CVDi CVI/CVS.

221 Chapter 10 I BASIC Keywords

NAME Statement

NAME old filename AS new filename

Renames old filename as new filename. With this statement, the data in the file is left unchanged. The new filename may not contain path, password, or drive specification. You can only rename a file in the current directory.

Example NQME "file.ba5" AS "f ile.old" BASIC renames file.bas as file.old.

222 Chawter 10 I BASIC Kevwords

NEW Statement

NEW

Deletes the program currently in memory and clears all vari- ables. NEW also closes all open files, turns off the trace function and resets the music background.

Example NEW

223 Chapter 10 I BASIC Keywords

NOISE Statement

NOISE source,volume,d uratwn

Generates noise through a TV monitor’s speaker (external speaker). Source is an integer in the range 0 to 7. It selects the type of noise. If source is in the range 0 to 3, periodic noise is selected. If source is in the range 4 to 7, white noise is selected.

Periodic White Frequency 0 4 35795451512 1 5 357954511824 2 6 357954512048 3 7 frequency of Voice 2 (see SOUND). Volume is an integer in the range 0 to 15 where 0 is the quietest and 15 is the loudest. Duration is a numeric expression in the range 0 to 65535. It sets the duration of the noise. A duration of 18.2 equals 1 second. You must execute a SOUND ON statement before using NOISE or BASIC returns an “Illegal function call” error.

Sample Programs 10 SOUND ON 20 FOR I = 0 TO 7 30 NOISE I, 15, 250 40 PLAY I1 I, II I, “V0” > , 50 NEXT I

224 Chapter 10 I BASIC Keywords

OCT$ Function

OCT$( num ber)

Returns the octal value of number. OCT$ returns a string that represents the octal value of a deci- mal number. The value returned is like any other string-it can- not be used in a numeric expression.

Examples PRINT OCT$C30), OCT$(S0), OCT$(90) prints the strings 36, 62, and 132.

Y$ = OCT$

225 ChaDter 10 I BASIC Kevwords

ON COM( ) GOSUB Statement

ON COM(channeZ) GOSUB line

Transfers program control to a subroutine beginning at line when activity occurs on the communication channel. Channel selects communications Channel 1 or 2. Line is the first line of the subroutine to be executed when activ- ity occurs on the specified communications channel. If you spec- ify Line 0, you turn off communications trapping. Use the RETURN statement to exit the subroutine. BASIC executes the ON COM( ) GOSUB statement only if a COM( ON statement has been previously executed to enable communication trapping. If a COM( ) STOP statement has been issued to halt communication trapping temporarily, BASIC exe- cutes the subroutine immediately after the next COM( 1 ON statement. When you execute the ON COM( ) GOSUB statement, BASIC immediately issues a COM( 1 STOP statement to prevent recur- sive traps. When BASIC executes the RETURN from the subrou- tine, it automatically executes another COM( ) ON statement to enable communication trapping again, unless the subroutine exe- cutes a COM( OFF statement.

226 Chapter 10 I BASIC Keywords

Example 10 COM(1) ON

200 ON COM(1 1 GOSUB 1000 Line 10 turns on communication trapping on Channel 1. After each program statement is executed, BASIC checks to see if the communication buffer contains characters. If it does, BASIC im- mediately executes the subroutine beginning at Line 1000. 10 COM(1) ON 20 ON COMC1) GOSUB 1000 30 FOR I = 1 TO 10 40 PRINT I 50 NEXT I

1000 ’ SUBROUTINE CODE

1050 RETURN 200 If activity occurs on Communication Channel 1 while the FOR/ NEXT loop is executing, BASIC immediately executes the sub- routine beginning at Line 1000. But the subroutine returns to Line 200 instead of completing the FORiNEXT loop. This results in a “For without next” error because any GOSUB, FOR, or WHILE statement remains active during key trapping. If the RETURN statement does not include a line number, pro- gram control returns to complete the FOR/NEXT loop, and no error occurs.

227 Chapter 10 I BASIC Keywords

ON ERROR GOTO Statement

ON ERROR GOTO line

Transfers control to line if an error occurs. This lets your program recover from an error and continue exe- cution. (Normally, you have a particular type of error in mind when you use the ON ERROR GOTO statement.) You must execute an ON ERROR GOTO before the error occurs. To disable it, execute an ON ERROR GOTO 0, which causes BASIC to stop execution and print an error message. This is rec- ommended for errors that are trapped and from which you can- not recover. Note: If an error occurs during execution of an error- handling routine, that error message is printed and execution terminates. Error trapping does not occur within the error handling routine. The error-handling routine must be terminated by a RESUME statement.

Example 10 ON ERROR GOTO 1500 branches program control to Line 1500 if an error occurs any- where after Line 10.

Sample Program See ERROR.

228 Chapter 10 I BASIC Keywords

ONIGOSUB Statement

ON n GOSUB Zine[,Zine,... I

Looks at n and transfers program control to the subroutine indi- cated by the nth line listed. For example, if n equals 1, BASIC branches to the first line listed; if n equals 2, BASIC branches to the second line listed. Line is the subroutine line at which execution begins when BASIC makes the branch. N must be a number in the range 0 to 255. If necessary, BASIC rounds n to an integer before evaluating it. If n is 0 or greater than the number of line numbers listed, BASIC continues with the next statement. If n is negative or is greater than 255, an “Illegal function call” error occurs. Use the RETURN statement to exit the subroutine. Example 10 ON Y GOSUB 1000, 2000, 3000 If Y equals 1, BASIC branches to a subroutine, beginning at Line 1000. If Y equals 2, BASIC branches to a subroutine, be- ginning at Line 2000. If Y equals 3, BASIC branches to a sub- routine, beginning at Line 3000. If Y is outside the range 1 to 3, BASIC either continues with the next statement or generates an “Illegal function call,” as men- tioned earlier.

229 Chapter 10 I BASIC Keywords

Sample Program 430 INPUT "CHOOSE 1, 2, OR 3" ; I 440 ON I GOSUB 500, 600, 700 450 END 500 PRINT "SUBROUTINE #I": RETURN 600 PRINT "SUBROUTINE #2": RETURN 700 PRINT "SUBROUTINE #3": RETURN

230 Chapter 10 I BASIC Keywords

ON/GOTO Statement

ON n GOTO line[,line,... I

Looks at n and transfers program control to the nth line listed. For example, if n equals 1, BASIC branches to the first line listed; if n equals 2, BASIC branches to the second line listed. N must be in the range 0 to 255. If necessary, BASIC rounds n to an integer before evaluating it. If n is 0 or is greater than the number of line numbers listed, BASIC continues with the next statement. If n is negative or is greater than 255, an "Illegal function call" error occurs. Example 10 ON MI GOTO 150, 160, 170, 150, 180 tells BASIC to evaluate MI. If MI equals 1, BASIC branches to Line 150; if MI equals 2, BASIC branches to Line 160; and so on. If MI is outside of the range 1 to 5, BASIC either continues with the next statement or generates an Illegal function call, as mentioned earlier.

Sample Program

5 REM MUST BE ON 10 INPUT "ENTER A,B, or C,";LS 20 L=CISC CLS) 30 ON L-64 GOTO 50, 60, 70 40 PRINT "TRY AGCI1N":GOTO 10 50 PRINT 91~0~TYPED 'A'~~:END 60 PRINT "YOU TYPED 'B'":END 70 PRINT "YOU TYPED 'C'":END

231 Chapter 10 I BASIC Keywords

ON KEY() GOSUB Statement ON KEY(number) GOSUB line

Transfers program control to a subroutine when you press the specified key. Number may be a number in the range 1 to 20, indicating the number of the key to trap. Function keys use their corresponding function key numbers. The cursor direction keys are numbered: m 11 El 12 El 13 El 14 User keys are numbered 15 through 20. User keys are defined with the KEY statement. Line is the first line number in the subroutine to execute when the specific key is pressed. If you specify Line 0, you turn off key trapping for that key. It is the same as executing a KEYO OFF statement. Use the RETURN statement to exit the subroutine. BASIC executes the ON KEYO GOSUB statement only if a KEYO ON statement has been executed previously to enable key trapping for that key. If a KEYO STOP statement has been issued to halt key trapping for that key temporarily, BASIC executes the subroutine immedi- ately after the next KEYO ON statement for that key. When you execute the ON KEY() GOSUB statement, BASIC im- mediately issues a KEYO STOP statement for that key to pre- vent recursive traps. When BASIC executes the RETURN from the subroutine, it automatically executes another KEY () ON statement for that key to enable key trapping again, unless the subroutine executes a KEYO OFF statement for that key.

232 Chapter 10 I BASIC Ke-ywords

Sample Program 10 KEY(5) ON 20 KEY(1) ON 30 ON KEY(5) GOSUB 80 40 ON KEY(1) GOSUB 100 50 FOR I = 1 TO 100 60 PRINT "NO KEY PRESSED" 70 NEXT 1:END 80 PRINT "KEY(5) PRESSED ************'I 90 RETURN 100 PRINT "KEY(1 PRESSED ; ; ; ; ; ; ; ;;;; ;'I 110 RETURN This program sets up [F51 and to be trapped.

233 Chapter 10 1 BASIC Keywords

ON PEN GOSUB Statement

ON PEN GOSUB line

Transfers program control to a subroutine when you activate the light pen. Line is the first line number in the subroutine to execute when the light pen is activated. If you specify Line 0, you turn off trapping for the pen. It is the same as executing a PEN OFF statement. Use the RETURN statement to exit the subroutine. BASIC executes the ON PEN GOSUB statement only if a PEN ON statement has been executed previously to enable light pen trapping. If a PEN STOP statement has been issued to halt trapping for the pen temporarily, BASIC executes the subroutine immediately after the next PEN ON statement. When you execute the ON PEN GOSUB statement, BASIC im- mediately issues a PEN STOP statement to prevent recursive traps. When BASIC executes the RETURN from the subroutine, it automatically executes another PEN ON statement to enable pen trapping again, unless the subroutine executes a PEN OFF statement.

234 Chapter 10 I BASIC Keywords

Example 10 PEN ON 20 ON PEN GOSUB 1000 30 REM

500 END 1000 REM PROCESSING ROUTINE

11 00 RETURN '30 Line 10 turns on pen trapping. After each program statement is executed, BASIC checks to see if the pen has been activated. If it has, BASIC immediately executes the subroutine at Line 1000.

235 Chapter 10 I BASIC Keywords

ON PLAY() GOSUB Statement

ON PLAY(number) GOSUB line

Transfers program control to a subroutine when the number of notes in the background music buffer goes from number to num- ber minus 1. This event trapping allows continuous music by let- ting you maintain a full music buffer. Number is an integer in the range 1 to 32, indicating that con- trol should transfer to line when the number of notes left in the music buffer is less than number. Line is the first line of the subroutine to execute when the num- ber of notes in the music buffer is less than number. If you spec- ify Line 0, you turn off play event trapping. Use the RETURN statement to exit the subroutine. BASIC executes the ON PLAY() GOSUB statement only when playing background music (PLAY “MB”) and if the PLAY ON statement has been executed to enable event trapping. If a PLAY STOP statement has been issued to halt event trap- ping temporarily, BASIC executes the subroutine immediately after the next PLAY ON statement. When you execute the ON PLAY() GOSUB statement, BASIC immediately issues a PLAY() STOP to prevent recursive traps. When BASIC executes the RETURN from the subroutine, it au- tomatically executes another PLAY0 ON statement to enable trapping again, unless the subroutine executes a PLAY0 OFF statement. Notes: BASIC does not issue a play event trap if the background music queue is already empty when you execute a PLAY ON. The PLAY statement is supported by a 32-element mu- sic queue. Given that “normal” and “staccato” notes are constructed from 2-note elements, the queue can contain as few as 16 notes or as many as 32 notes.

236 Chapter 10 I BASIC Keywords

Therefore, select conservative values for the trap num- ber. For example, if number is set at 32, event traps might happen so often that there is little time to exe- cute the rest of your program. It is suggested that the trap number be less than 16 for better performance.

Example 10 PLAY ON 20 ON PLAY(2) GOSUB 1000 30 REM

500 END 1000 REM PROCESSING ROUTINE

1100 RETURN 30

Line 10 turns on play trapping. After each program statement is executed, BASIC checks to see if the number of notes in the mu- sic buffer is less than 2 notes. If it is, BASIC immediately exe- cutes the subroutine at Line 1000.

237 Chapter 10 I BASIC Keywords

ON STRIG() GOSUB Statement

ON STRIG(number) GOSUB line

Transfers program control to a subroutine when you press one of the joystick’s buttons. Number specifies the number of the button pressed and is one of the following: 0 left joystick, button 1 2 right joystick, button 1 4 left joystick, button 2 6 right joystick, button 2 Line is the first line number of the subroutine to be executed when you press one of the joystick’s buttons. If you specify Line 0, you turn off trapping for the joysticks. Use RETURN to exit the subroutine. BASIC executes the ON STRIGO GOSUB statement only if a STRIG ON statement has been executed previously to enable joystick trapping. If a STRIG STOP statement has been issued to halt joystick trapping temporarily, BASIC executes the subroutine immedi- ately after the next STRIG ON statement. When the ON STRIGO GOSUB statement is executed, BASIC immediately issues a STRIG STOP statement to prevent recur- sive traps. When BASIC executes the RETURN from the subrou- tine, it automatically executes another STRIG ON statement to enable joystick button trapping again, unless the subroutine exe- cutes a STRIG OFF statement.

238 Chawter 10 I BASIC Kevwords

Sample Program 5 STRIG(0) ON: STRIG(2) ON 10 ON STRIGC0) GOSUB 1000 20 ON STRIGC2) GOSUB 2000 30 PRINT "Press one of the joystick buttons." 40 FOR I = 1 TO 3000:NEXT I 50 GOTO 30 1000 PRINT "You pressed the left button." :RETURN 2000 PRINT "You pressed the right button." : RETURN Lines 10 and 20 turn on joystick trapping. Line 30 instructs you to press one of the buttons. Line 40 waits for you to press a but- ton. If you press the left button, BASIC transfers program control to the subroutine at Line 1000. If you press the right button, BASIC transfers program control to the subroutine at Line 2000. If you do not press a button, Line 50 returns to print the mes- sage again. This program is a continuous loop. To end the pro- gram, press [CTRL]m].

239 Chapter 10 I BASIC Keywords

ON TIMER() GOSUB Statement

ON TIMER(number1 GOSUB line

Transfers program control to a subroutine when the specified pe- riod of time has elapsed. Number indicates the number of seconds. Number may be a value in the range 1 to 86400 (86400 seconds = 24 hours). Line is the first line number in the subroutine to execute when the specified time has passed. If you specify Line 0, you turn off trapping for the timer. Use RETURN to exit the subroutine. BASIC executes the ON TIMER0 GOSUB statement only if a TIMER ON statement has been executed previously to enable time event trapping. If a TIMER STOP statement has been issued to halt time event trapping temporarily, BASIC executes the subroutine immedi- ately after the next TIMER ON statement. When you execute the ON TIMER() GOSUB statement, BASIC immediately issues a TIMER STOP to prevent recursive traps. When BASIC executes the RETURN from the subroutine, it au- tomatically executes another TIMER ON statement to enable trapping again, unless the subroutine executes a TIMER OFF statement.

240 Chapter 10 I BASIC Keywords

Example 10 TIMER ON 20 ON TIMER (60) GOSUB 1000 30 REM

500 END

1000 REM PROCESSING ROUTINE

1100 RETURN 30 Line 10 turns on timer trapping. After each statement is exe- cuted, BASIC checks to see if the specified time has elapsed. If it has, BASIC immediately executes the subroutine at Line 1000.

241 Chapter 10 I BASIC Keywords

OPEN Statement

OPEN mode,[#]buffer,[pathname][dev:][,record length] OPEN [pathname][dev:l[FOR model AS [#]buffer [LEN = record length1

Establishes an input/output path for a file or device. Buffer is an integer in the range 1 to 15. It specifies the 110 buffer in memory to use when accessing the file. The number sign (#) is optional. It is provided for compatibility with other BASICs. Pathname is a standard file specification as described in Chapter 1. If you omit pathname, you must include deu:. deu: specifies the device to be opened for communication. Record length is an integer in the range 1 to 32768 that sets the record length for direct access files. If you omit record length, BASIC assumes a default record length of 128 bytes. Do not use this option with sequential access files. Mode specifies any of the following: 0 or OUTPUT sequential output mode I or INPUT sequential input mode A or APPEND sequential output and extend mode R or RANDOM direct inputloutput mode In the first form of the syntax, you must use the abbreviated form of mode, and it must be enclosed in quotation marks. In the second form of the syntax, you must specify the complete word for mode. You may not specify RANDOM. If you want to use direct access in the second form of the syntax, omit mode.

242 Chapter 10 I BASIC Kevwords

You may open a file for output in only one buffer at a time. Once you assign a buffer to a file with the OPEN statement, you can- not use that buffer in another OPEN statement until you close the first file. However, BASIC lets you access the same file for in- put by opening it in different buffers. You may keep several rec- ords from the same file in memory for quick access. If you open a file for input that does not exist, BASIC returns a "File not found" error. If you open a file for output that does not exist, BASIC creates the file. If you open a file for append that does not exist, BASIC creates the file and sets the mode to RANDOM. If you open a file for direct access with a record length that does not match the record length assigned to the file when it was cre- ated, an error occurs. Examples OPEN "R", 2, "test .dat" opens the file test.dat in direct access mode, using Buffer 2. If test.dat does not exist, BASIC creates it on the current drive. The record length is 128 bytes.

OPEN "LPTI :I' FOR OUTPUT AS 2 opens the printer for sequential output using Buffer 2. OPEN "A:\PAYROLL\data.ba3" FOR INPUT AS 1 opens the file databas in the PAYROLL directory on Drive A for sequential input using Buffer 1.

243 Chapter 10 I BASIC Ke.ywords

OPEN/C ommunications Statement

OPEN “COMchan~l:[speed] [,purity1 [,datul[,stopl [,RSI[,CS[secondsl][,DS[secondslj[,CD[seconds]j[,m&] [,PEl [,LFl” AS [#lbuffer[LEN = number]

Opens a file and allocates a buffer for RS-232C (Asynchronous Communications Adapter) communication. Channel can be 1 or 2 to select the communications channel to be opened. Speed is an integer specifying the transmit and receive rate in bits per second (bps). Valid speeds are 75, 110, 150, 300, 600, 1200, 2400, 4800, and 9600. If you omit speed, BASIC sets the speed at 300 bps. Parity is a constant specifying the parity to be used when the data is transmitted and received. The constant must be one of the following: E EVEN transmit parity, EVEN receive parity checking. 0 ODD transmit parity, ODD receive parity checking. M parity bit always transmitted and received as a mark (1 bit). S parity bit always transmitted and received as a space (0 bit). N no transmit parity, no receive parity checking. If you omit parity, BASIC assumes E (EVEN). Data is an integer specifying the number of transmit and re- ceive bits. Valid values are 5, 6, 7, and 8. If you do not specify data, BASIC assumes 7. Note: Eight data bits with parity is illegal. Stop must be either 1 or 2 to indicate the number of stop bits. If you omit stop, 75 and 110 bps transmit 2 stop bits, and all other speeds transmit 1 stop bit.

244 Chapter 10 I BASIC Keywords

Buffer is a number in the range 1 to 15, indicating the buffer that accesses the file. The number sign (#) is optional. It is pro- vided for compatibility with other BASICs. Number specifies the maximum number of bytes that can be ac- cessed in the communications buffer by GET and PUT state- ments. If you omit the LEN option, BASIC assumes 128 bytes. The parameters speed, parity, data, and stop are all positional. That is, they must be in the order specified in the syntax. If you omit one of the parameters, you must still include the comma to hold its position. The remaining parmeters are not positional. They may be in any order, or you may omit them. They control the software commu- nication signal lines between 2 terminals. If you omit the CS, DS, or CD options, the signals are not checked at all. Include them only if you are testing these software signals. The RS option suppresses the Request To Send (RTS) signal. Re- quest To Send is a signal that is sent from the sending terminal to the receiving terminal to ensure that the receiving terminal is ready to accept communication data. When you execute an OPEN COM statement, the RTS line is turned on, unless you in- clude the RS option. The CS option controls the Clear To Send (CTS) signal which is sent from the receiving terminal to the sending terminal to let the sending terminal know that the receiving terminal is ready to receive. You can think of RTS and CTS as a hand-shaking exercise, in which the 2 terminals let each other know that they are ready to send and/or receive data. RTS is an output signal from the send- ing terminal, and CS is an input signal to the sending terminal. The DS option controls the Data Set Ready (DSR) signal. The DSR signal ensures that a data set, such as a modem, is present to transmit the data. The CD option controls the Carrier Detect (CD) signal. The CD signal is an input signal which ensures that the data set is ready to transmit the data.

245 Chapter 10 I BASIC Keywords

The seconds argument in the CS, DS, and CD options specifies the number of milliseconds to wait for the signal before return- ing a “Device Timeout” error. Seconds may be in the range 0 to 65535. If you omit seconds or specify a zero, the signal is not checked. If you specify RS, seconds defaults to zero for CS. If you omit RS, the default for CS is 1000. Either an RS or a CS is required. That is, if you omit RS, the Clear To Send signal is not checked. If you include RS, OPEN COM waits 1 second for CS before issu- ing a “Device Timeout” error. If you omit seconds after the DS option, the default value is 1000, and OPEN COM waits 1 second before issuing a “Device Timeout” error. If you omit seconds after CD, the default is zero and the signal is not checked. IiO statements to a communications file do not execute if these signals are off. The system waits 1 second before returning a “Device Timeout” error. Specifying these options lets you ignore these signals or specify the length of time to wait for the signal. The LF option sends a line feed character after every carriage return. This is useful if you are printing the communication data to a serial line printer. A line feed is also sent after the carriage return that is the result of the width setting. Note that when you specify the LF option, INPUT# and LINE INPUT# stop when they read a carriage return and ignore the line feed. Mode specifies the type of data that is transmitted. It may be either BIN for binary mode or ASC for ASCII mode. If you omit mode, OPEN COMl opens the device in binary mode. If you specify the BIN mode, OPEN COM does not expand tabs to spaces, does not force a carriage return at the end of the line, does not recognize Control Z as an end-of-file, and ignores the LF option. If you specify the ASC mode, OPEN COM expands tabs to spaces, forces a carriage return at the end of the line, and recog- nizes Control Z as the end-of-file. When you close the channel, Control Z is sent over the RS-232 line.

246 Chapter 10 I BASIC Keywords

The PE option enables parity checking. With the option on, par- ity errors cause Device IiO errors and turn on the high order bit for 7 or fewer data bits. The default is no parity checking. Fram- ing and overrun errors always cause Device IiO errors and turn on the high order bit, regardless of whether or not you use the PE option.

Examples OPEN "CUM1 :" AS 1 opens Buffer 1 for Communications Channel 1 at a rate of 300 bps with even parity, 7 data bits, and 1 stop bit. RTS is sent. OPEN "COM2:9600,N,8,1 ,BIN" AS 2 opens Buffer 2 for Communications Channel 2 at a rate of 9600 bps with no parity, 8 data bits, and 1 stop bit. The data is binary. OPEN "COM1 : 4800,, , ,CS3000,DS2000" AS 1 opens Buffer 1 for Communications Channel 1 at a rate of 4800 bps with even parity, 7 data bits, and 1 stop bit. RTS is sent. OPEN COM issues a "Device Timeout" error if there is no CS signal after 3 seconds and no DS signal after 2 seconds. Note that even though parity, data, and stop are not included, the commas are required.

247 Chapter 10 I BASIC Keywords

OPTION BASE Statement

OPTION BASE value

Sets value as the minimum value for an array subscript. Value may be 1 or 0. The default is 0. If you use this statement in a program, it must precede the DIM statement. If the statement: OPTION BFISE 1 is executed, 1 is the lowest value an array subscript may have.

248 Chapter 10 I BASIC Keywords

OUT Statement

OUTport, data byte

Sends a data byte to a machine output port. A port is an input/ output location in memory. Port is an integer in the range 0 to 65535. Data byte is an integer in the range 0 to 255.

Example OUT 32,100 sends 100 to port 32.

249 Chapter 10 I BASIC Ke.ywords

PAINTlGraphics Statement

Fills in an area on the display with a selected color or pattern. (x,y) specify the coordinates where the painting begins. x is the horizontal coordinate, and y is the vertical coordinate. Color can be either a number.or a string expression. If color is a number it specifies a color number available in the current screen mode. If color is a string expression, it specifies the mask to be used for tiling. The tiling mask describes a pattern to be used when painting and is in the form: CHR$(&Hnn)+CHR$(&Hnn)+CHR$(&Hnn) ... Border specifies the border color at which to stop painting, and must be a color number in the current palette. If you omit bor- der, BASIC assumes the value of color. See Chapter 8, “Displaying Color and Graphics,” for information on coordinates and colors for the current screen mode. Background is a 1-byte string expression specifying which color to skip when checking for borders while paint tiling. BASIC begins to change the color of pixels at the point you spec- ify with x and y coordinates. BASIC continues to change the color of every pixel that is not the same color as color. When BASIC paints 1 line of pixels without changing the color of any pixel in that line, PAINT is complete. However, you may continue past this point while tile painting. The background option tells PAINT what background tile pattern or color byte to skip when checking for the boundary.

250 Chapter 10 I BASIC Keywords

This means that instead of stopping when 1 line of points has been painted without changing the color, PAINT can continue, if you specify background. For example, normally you cannot draw alternating blue and red lines on a red background because PAINT stops after painting the first red line. However, by speci- fying red as the background color (&HAA), you can draw the red line over the red background. PAINT must start on a nonborder point. If the point is already border or color color, BASIC does not execute the PAINT statement. PAINT can fill any figure, but painting jagged edges or very complex figures may result in an “Out of memory” error. If this happens, you must use the CLEAR statement to increase the amount of stack space available.

Tiling Tiling lets you select a pattern to be used when painting an area on the screen. The tile mask is 8-bits wide and may be a maxi- mum of 64 bytes long: X,Y 8 7 6 5 4 3 2 1 tile byte 0,0 ...... 1 0,1 ...... 2 012 ...... 3 073 ...... 4

0,63 ...... 64

Each byte in the mask represents 8 points along the horizontal row and 1 point along the vertical row. PAINT repeats the tile mask pattern (horizontally and vertically) to create a uniform pattern over the entire area being painted.

251 Chapter 10 I BASIC Keywords

In high resolution graphics, 1 bit of the tile mask equals 1 point on the screen. Therefore, each position in the tile mask with the bit value one (1) is drawn. You can paint a pattern of Xs with this tile mask: byte 87654321 0 10000001 CHR$(&H81) 1 01000010 CHR$(&H42) 2 00100100 CHR$(&H24) 3 00011000 CHR$(&H18) 4 00011000 CHR$(&H18) 5 00100100 CHR$(&H24) 6 01000010 CHR$(&H42) 7 10000001 CHR$(&H81) In 4-color graphics, 2 bits correspond to each point on the screen. That is, each byte of the tile mask describes only 4 points. These 2 bits describe the color for the point being drawn. The following chart shows the values for the given colors. Remember, Color 0 is the set background color. (See COLOR.) Palette Palette binary 0 1 value green cyan 01 red magenta 10 brown white 11 The following tile mask sets up a star pattern in green and brown using Palette 0 or in cyan and white using Palette 1. BYTE 0 01 00 00 01 CHR$(&H41) 1 00 01 01 00 CHR$(&H14) 2 11 11 11 11 CHR$(&HFF) 3 00 01 01 00 CHR$(&H14) 4 01 00 00 01 CHR$(&H41) In 16-color graphics (Modes 3 and 5), 4 bits correspond to each point on the screen. That is, each byte of the tile mask describes only 2 points.

252 Chapter 10 I BASIC Keywords

PALETTE/Graphics Statement

PALETTE [color,dispZaycolor]

Changes the color associated with a particular color number in the current palette. Color specifies the color number in the current palette you want to change. It is an integer in the range 0 to 15. See Chapter 8, “Displaying Color and Graphics,” for information on colors in the current screen mode. Display color specifies the new color you want BASIC to display when color is specified. Display color may be a number in the range 0 to 15 as described in Chapter 8, “Displaying Color and Graphics .” For example, in Screen Mode 3, Color 1 is blue. You can use the PALETTE statement to change it so that Color 1 is associated with a different color. For example, use this statement to change Color 1 to magenta: PALETTE 1 ,5 When you execute a PALETTE statement to change the default values, the new values remain in effect until you execute another COLOR/Graphic, PALETTE or PALETTE USING statement. A PALETTE statement without parameters forces the position numbers to return to their default values. You can change only 1 position in the palette each time you exe- cute a PALETTE statement. To change more than 1 position in a palette, see the PALETTE USING statement.

253 Chapter 10 I BASIC Ke.ywords

Example PALETTE 3,7 changes the third position from cyan to gray. PALETTE changes all positions in the current palette to their default values.

Sample Program 5 SCREEN 1 10 COLOR 0,0 20 PALETTE 3,l 30 LINE (0,1-00) - (319,100),3 40 PAINT (1 ,100),3,6 50 PALETTE Line 10 selects Palette 0 as the current palette. Line 20 changes position Number 3 from brown to blue. Line 30 draws a horizon- tal blue line across the center of the screen. Line 40 colors the lower half of the screen blue. Line 50 causes the palette to re- turn to its original value. Position 3 is now brown again.

254 Chawter 10 I BASIC Kevwords

PALETTE USING/Graphics Statement

PALETTE USING array(subscrippt)

Changes the colors associated with more than 1 of the color numbers in the current palette. Array is the name of an integer array in which you define the order in which colors are to be put in the current palette. Subscript is the array position that contains the value of the color that you want put in the first palette position. After BASIC assigns that value to the first position, it assigns the remaining array values to the remaining palette positions. Therefore, when you create the array, have at least 16 elements following sub- script so that PALETTE USING has enough colors to fill the palette. The array can be larger than the palette. PALETTE USING stops filling the current palette when it reaches the last position in the palette. To create the array, load a color number into each element. Group color numbers that you use most often. For example, if you use 2 shades of blue with 2 shades of green, place their color numbers adjacent in the array, like this: Subscript Color 0 2 (Green) 1 10 (Light Green) 2 1 (Blue) 3 9 (Light Blue) In the statement: PALETTE USING AC0) Color 0 becomes green, Color 1 becomes light green, Color 2 be- comes blue, and Color 3 becomes light blue. If you assign a value of -1 to a position in the array, PALETTE USING does not change the corresponding color from its previous value.

255 Chapter 10 1 BASIC Keywords

The array may be larger than the palette. PALETTE USING stops filling the current palette when it reaches the last position in the palette. If you use the 2 shades of blue with the 2 shades of red, and also use the 2 shades of blue with the 2 shades of cyan, you can put the numbers for the shades of blue in your array as often as you need them. You can expand the previous array, for example: Subscript Color 0 2 (Green) 1 10 (Light Green) 2 1 (Blue) 3 9 (Light Blue) 4 4 (Red) 5 12 (Light Red) 6 9 (Light Blue) 7 1 (Blue) 8 3 (Cyan) 9 11 (Light Cyan)

Examples PALETTE USING A(2) loads the palette with the blues and reds. Color 1 is still blue. Color 2 becomes light blue, Color 3 becomes red, Color 4 becomes light red. PALETTE USING A(4) puts the same colors in the palette in a different order. In this case, Color 1 becomes red, Color 2 becomes light red, Color 3 be- comes light blue, Color 4 becomes blue.

256 Chawter 10 I BASIC Kevwords

PCOPY Statement

PCOPY source page,destinatwn page

Copies one video page to another. Source page is an integer representing a video page in memory to be copied. The range depends on the current screen mode and the amount of video memory. Destination page represents the video page to receive the copy. Its requirements are the same as source page.

Example PCOPY 3,5 copies the contents of Video Page 3 to Video Page 5.

257 Chawter 10 I BASIC Kevwords

PEEK Function

PEEK(mmry location)

Returns a byte from memory location Memory location must be in the range -32768 to 65535. The value returned is an integer in the range 0 to 255. (For the interpretation of a negative value of memory location, see the VARPTR statement.) PEEK is the complementary function of the POKE statement.

Example

A = PEEK (6HSA00) BASIC returns the value stored at address 5A00 and stores it in variable A.

258 Chapter 10 I BASIC Keywords

PEN Function

PEN(num ber)

Returns the light pen’s coordinates. Number is a number in the range 0 to 9 that tells BASIC what to return. Values 0-5 return x,y coordinates corresponding to the current screen mode. Values 6-9 return the character row or col- umn position. 0 Returns a -1 if pen button has been pressed since last poll. Returns a 0 if not. 1 Returns the x coordinate (horizontal) where the pen was last activated. 2 Returns the y coordinate (vertical) where the pen was last activated. 3 Returns a -1 if the pen button is being pressed. Re- turns a 0 if it is up. 4 Returns the last known valid x coordinate (horizontal). 5 Returns the last known valid y coordinate (vertical). 6 Returns the character row position where the pen was last activated. 7 Returns the character column position where the pen was last activated. 8 Returns the last known character row position. 9 Returns the last known character column position. You must execute a PEN ON statement before executing the PEN function. If you do not, an “Illegal function call” error occurs.

Example

A = PENC1) returns the x coordinate of the pen.

259 Chapter 10 I BASIC Keywords

PEN/Trap Statement

PEN action

Turns on, turns off, or temporarily halts light pen event trapping, Actwn may be any of the following: ON enables event trapping OFF disables event trapping. STOP temporarily suspends event trapping. Use the PEN/Trap statement in a light pen trap routine with the ON PEN statement to detect when the light pen has been activated. The PEN ON statement turns on the trap. BASIC checks after each program line to see if the light pen has been activated. If so, BASIC transfers program control to the line number specified in the ON PEN GOSUB statement. The PEN STOP statement temporarily halts light pen trapping. If the light pen is activated, BASIC does not transfer program control to the ON PEN GOSUB statement until you turn on trapping again by executing a PEN ON statement. BASIC re- members that the light pen was activated and branches to the subroutine immediately after trapping is turned on again. The PEN OFF statement turns off light pen trapping. BASIC does not remember if the light pen was activated when trapping is turned on again. You must also use PEN ON before executing the PEN function. See ON PEN GOSUB for more information about light pen trapping.

260 Chapter 10 I BASIC Ke-ywords

PLAY Statement

PLAY string [,[string1[,string11

Plays the musical notes specified by string. PLAY supports 3 separate strings to allow independent control of each of 3 voices. String is a string expression consisting of 1 or more single-char- acter music commands. String must be enclosed in quotation marks. The single character music commands are: A-G plays notes A through G of one musical scale. You may include an optional number sign (#) or plus sign ( +) to indicate a sharp note or a minus sign (-) to indicate a flat note. You may only specify sharp or flat notes that correspond to the black keys on a piano. The letters A, C, D, F, and G may be followed by a plus because they are followed by black keys on a piano. The letters A, B, D, E, and G may be followed by minus be- cause they are preceded by black keys on a piano. Ln sets the duration of the notes that follow. n may be a value in the range 1 to 64. Here are a few of the more common lengths: 1 indicates a whole note. 2 indicates a half note. 4 indicates a quarter note. 8 indicates an eighth note. 16 indicates a sixteenth note. If you want to change the duration for only 1 note, place n immediately after the note, omit- ting the L. For example, A16 is equivalent to L16A. On sets the current octave. There are 7 octaves, 0 through 6. Each octave starts with C and ends with B. Octave 3 starts with middle C. If you omit n, BASIC assumes Octave 4.

261 Chapter 10 I BASIC Keywords

> Changes the current octave to the next higher octave. < Changes the current octave to the next lower octave. Nn plays a note. n may be in the range 0 to 84. In the 7 possible octaves, there are 84 notes. Instead of specifying the letter and the octave of the note, you may specify its number 1 to 84. Specifying zero means rest. Pn rests. n may be in the range 1 to 64 and has the same meaning as n with the L option. Tn sets the number of quarter notes in 1 minute. n may be in the range of 32 to 255. If you omit n, BASIC assumes 120 quarter notes in 1 minute. That is a moderate tempo. See the SOUND statement for information on beats per minute for common tempos. plays as a dotted note. BASIC plays the note one- half its length longer. You may use more than one dot after each note. BASIC scales the length of time accordingly. Dots may also appear after the P option to scale the length of the rest. MF plays the music in the foreground, which includes sounds made by both PLAY and SOUND. This means that each subsequent note or sound does not start until the previous note or sound is fin- ished. If you omit MF and MB, BASIC assumes MF. MB plays the music in the background, which in- cludes sounds made by both PLAY and SOUND. This means that each note or sound is placed in a buffer allowing the BASIC program to continue execution while music plays in the background. A maximum of 32 notes and/or rests can play in background at a time. MN sets “music normal”; each note plays 718 of the duration as set by the L option. If you omit MN and MS, BASIC assumes MN.

262 Chapter 10 I BASIC Keywords

ML sets "music legato"; each note plays the full du- ration as set by the L option. MS sets "music staccato"; each note plays 3/4 of the duration as set by the L option. X variable; executes a substring. The X command lets you execute a second substring from a string, much like GOSUB. You can have one string execute another, which executes a third, and so on. Vari- able is a string variable in your program that contains the substring you want to execute. Vari- able may contain an X command to execute an- other substring. The semicolon after the variable name is required. Vn sets the volume. n must be in the range 0 to 15. You must execute a SOUND ON statement to use this option. If you omit volume, BASIC uses 8. With the 0, N, P, and T commands, n may also be a numeric variable in your BASIC program. Do not space between the com- mand and the n or between the command and the variable. You must include a semicolon after the variable name. The lowest note the multi-voice sound chip can produce is Note A of Octave 0, which is 110Hz. If you try to play a lower note, BASIC does not return an error. Instead, BASIC plays Note A of Octave 0.

Ex ample 1 0 PLAY "C4F. C8F8. C16F8. G16A2F2" 20 INPUT "CAN YOU NAME THAT TUNE ";A$ 40 IF A$ = "THE EYES OF TEXAS" THEN GOTO 50 ELSE PRINT "TRY AGAIN": GOTO 10 50 PRINT "THAT'S RIGHT!"

263 Chapter 10 I BASIC Keywords

PLAY Function

PLAY (number)

Returns the number of notes currently in the background music queue. Number is a dummy argument when SOUND is OFF. If you exe- cute a SOUND ON, then number may be one of the following: 0 returns the number of notes left to play on voice channel 0. 1 returns the number of notes left to play on voice channel 1. 2 returns the number of notes left to play on voice channel 2. If you specify a number other than 0-2, BASIC assumes 0. The PLAY function returns a 0 when the program is running in music foreground mode. See also SOUND

Sample Program 10 PLAY "ME ABCDEFG" 20 IF PLAY (0) = 4 GOTO 40 30 GOTO 20 40 PLAY "GFEDCBA" Line 10 sends notes to the music buffer. When the number of notes is less than 4. Line 40 sends more notes to the buffer.

264 Chapter 10 I BASIC Keywords

PLAY/Trap Statement

PLAY action

Turns on, turns off, or temporarily halts background music event trapping. Action may be any of the following: ON enables play event trapping.

OFF disables play event trapping.

STOP temporarily suspends play event trapping. Use the PLAY/Trap statement in a background music trap rou- tine with the ON PLAY GOSUB statement to detect when the number of notes in the background music queue goes from num- ber to number minus 1. The PLAY ON statement turns on the trap. BASIC checks the number of notes in the background music queue after each pro- gram line. If the number is equal to that in the ON PLAYO GO- SUB statement, BASIC transfers program control to the line number specified. The PLAY STOP statement temporarily halts background music trapping. If the number of notes equals the specified number, BASIC does not transfer program control to the ON PLAYO GO- SUB statement until you turn on trapping again by executing a PLAY ON statement. BASIC remembers that the number of notes was equal and branches to the subroutine immediately after trapping is turned on again. The PLAY OFF statement turns off background music trapping. BASIC does not remember if the number of notes in the queue is equal to the number specified when trapping is turned on again. See ON PLAYO GOSUB for more information about background music trapping.

265 Chapter 10 I BASIC Ke.ywords

PMAP Function

PMAP(coordinate,action)

Returns the physical or world coordinate for the specified coordi- nate. Coordinate is any x- or y-coordinate. If coordinate is a physical coordinate, it must be within the limits of the screen. If coordi- nate is a world coordinate, it may be any single precision floating point number. Action is one of the following: 0 returns the physical x-coordinate for the specified world coordinate. 1 returns the physical y-coordinate for the specified world coordinate. 2 returns the world x-coordinate for the specified physi- cal coordinate. 3 returns the world y-coordinate for the specified physi- cal coordinate.

Example A = PMAP(200,B) returns the physical x-coordinate of the world coordinate 200 and places it in A.

266 Chawter 10 I BASIC Kevwords

POINT/Graphics Function

POINT (x,y) POINT (action)

Returns the color number of a point on the screen or returns the current physical or world coordinates. (x,y) specify the coordinates of the point. x is the horizontal point, and y is the vertical point. The x and y coordinates must be absolute values. If you specify a point that is out of range, BASIC returns a -1. See Chapter 8, “Displaying Color and Graphics,” for information on coordinates for the current screen modes. Action is one of the following: 0 returns the current physical x-coordinate (horizontal). 1 returns the current physical y-coordinate (vertical). 2 If WINDOW is active, returns the world x-coordinate. Otherwise, returns the physical x-coordinate. 3 If WINDOW is active, returns the world y-coordinate. Otherwise, returns the physical y-coordinate. When retrieving the color number, POINT returns the color number as it is defined in the current palette. Example 10 SCREEN 2 20 IF POINT (1 ,1)<>0 THEN PRESET (1 ,I1 ELSE PSET (1 ,I) If point 1,l is any foreground color, PRESET changes it to the background color. If the point is the background color, PSET changes it to Color 3. 10 SCREEN 1 20 X=POINT (0):Y=POINT(I) 30 PRINT X,Y BASIC prints the coordinates of the graphics cursor.

267 Chapter 10 I BASIC Keywords

POKE Statement

POKE memory location, data byte

Writes data byte into memory location. Both memory location and data byte must be integers. Memory lo- cation must be in the range -32768 to 65535. POKE is the complementary statement of PEEK. The argument to PEEK is a memory location from which a byte is to be read. PEEK and POKE are useful for storing data efficiently, loading assembly-language subroutines, and passing arguments (or re- sults) to and from assembly-language subroutines. See also VARPTR.

Example POKE &H5A00, CHFF writes a hexadecimal FF into memory location 5A00.

268 Chapter 10 I BASIC Keywords

POS Function

POS(number)

Returns the current column position of the cursor. Number is a dummy argument. POS returns a number in the range 1 to 80, indicating the cur- rent cursor-column position on the display.

Example PRINT TFIB(40) POS(0) prints 40. The PRINT TAB statement moves the cursor to Posi- tion 40; therefore, POS(0) returns the value 40. (However, be- cause a blank is inserted before the “4” to accommodate the sign, the “4” is actually at Position 41.) Sample Program 150 CLS 160 FIF = INKEYF 170 IF A$ = I”’ THEN 160 180 IF POS(X) > 70 THEN IF A$ = CHRF(32) THEN FIB = CHRF(13) 200 LPRINT FIB; 210 GOT0 160 This program lets you use your printer as a typewriter (except that you cannot correct mistakes). Your computer keyboard is the typewriter keyboard. Everything you type is printed on your printer. The program also makes sure that no word is divided between two lines.

269 Chapter 10 I BASIC Keywords

PRINT Statement

PRINT data[,data,...I

Prints numeric or string data on the display. You can substitute a question mark (?) in place of the word PRINT. Data is any numeric or string constant or variable. If you omit datu, BASIC prints a blank line. If you specify more that 1 data item in the statement, separate them by commas, semicolons, or spaces. If you use commas, the cursor automatically advances to the next tab position before printing the next item. (BASIC divides each line into print zones containing 14 positions each, at col- umns 14, 28, 42, 56, and 70.) If you use semicolons or spaces to separate the data items, PRINT prints the items without any spaces between them. BASIC begins the next PRINT item where the last one stopped. If no trailing punctuation is at the end of the PRINT statement, the cursor drops to the beginning of the next line. If BASIC tries to print a string longer than it can fit on the cur- rent line, it moves to the next line and prints the string. Single precision numbers with 7 or fewer digits that can be accu- rately represented are printed in regular format rather than ex- ponential format. For example, 1E-7 is printed as .0000001; 1E-8 is printed as 1E-08. Double precision numbers with 16 or fewer digits that can be ac- curately represented are printed in regular format rather than exponential format. For example, 1D-15 is printed as .000000000000001; 1D-16 is printed as 1D-16. BASIC prints all numbers with a trailing blank and prints posi- tive numbers with a leading blank. Negative numbers are pre- ceded by a minus sign. String constants must be enclosed in quotation marks.

270 Chapter 10 I BASIC Ke-ywords

Examples PRINT "DO"; "NOT"; "LEAVE"; "SPACES"; "BETWEEN"; "THE S E " ; "W URDS" displays DONOTLEAVESPACESBETWEENTHESEWORDS

Sample Program 60 INPUT "ENTER THIS YEAR"; Y 70 INPUT "ENTER YOUR AGE";A 80 INPUT "ENTER f? YEAR IN THE FUTURE";F 90 N=A + (F - Y) 100 PRINT "IN THE YEAR"F-YOU WILL BE"N"YEARS OLD" Because F and N are positive numbers, PRINT inserts a space before and after them; therefore, your display should look similar to this (depending on your input): IN THE YEAR 2004 YOU WILL BE 46 YEARS OLD If we had separated each expression in Line 100 by a comma: 100 PRINT "IN THE YEAR",F,"YOU WILL BE",N,"YEARS OLD" BASIC would move to the next tab position after printing each data item.

271 Chapter 10 I BASIC Keywords

PRINT USING Statement

PRINT USING format; data[,data,... I

Prints data using a format you specified. This statement is espe- cially useful for printing report headings, accounting reports, checks, or any other documents that require a specific format. Format consists of 1 or more field specifierb), or any alphanu- meric character. Format must be enclosed in quotation marks. Data may be string and/or numeric value(s1. If you specify more than 1 data item in the statement, use the same separators as described in PRINT. With PRINT USING, you may use certain characters called field specifiers, to format the field. You may use more than 1 field spe- cifier, except as indicated. Specifiers for String Fields: ! prints the first character in the string only

PRINT USING 'I!"; "PERSONNEL" BASIC prints P. \spaces \ prints 2 + n characters from the string (n is the num- ber of spaces between the slashes). If you type the backslashes without any spaces, BASIC prints 2 char- acters; with one space, BASIC prints 3 characters, and so on. If the string is longer than the field, the extra characters are ignored. If the field is longer than the string, the string is left-justified and padded with spaces on the right. PRINT USING "\BBB\"; "PERSONNEL" BASIC prints PERSO & prints the string without modifications. 10 A$="TAKE":B$="RACE" 20 PRINT USING "!";A$; 30 PRINT USING "&";E$ When this program is run, BASIC prints TRACE.

272 Chapter 10 I BASIC Keywords

Specifiers for Numeric Fields: # prints the same number of digit positions as number signs (#I. Numbers are rounded as necessary. You may insert a decimal point at any position. BASIC always prints the digits preceding the decimal point. If there is no number, BASIC prints a zero. If the number to be printed has fewer digits than posi- tions specified, the number is right-justified (preceded by spaces). If the number to be printed is larger than the specified numeric field, a percent sign (%) is printed in front of the number.

PRINT US I NG 'I##.##'I; 1 1 1 .22 PRINT US I NG 'I##.##'I; .75 PRINT US I NG I.###.##";876.567 BASIC prints %111.22, 0.75 and 876.57, respectively. If the number of digits specified exceeds 24, an "Illegal function call" occurs. + prints the sign of the number. The plus sign may be typed at the beginning or at the end of the format string.

PRINT USING 'I+##.## 'I; -98.45,3.50,22.22,-.9 BASIC prints: -98.45 + 3.50 + 22.22 -0.90

PRINT USING 'I##.##+'I; -98.45,3.50,22.22,-.9 BASIC prints: 98.45- 3.50 + 22.22 + 0.90- (Note the use of spaces at the end of a format string to separate printed values.) - prints a negative sign after negative numbers (and a space after positive numbers).

PRINT USING lo###.#-"; -768.668 BASIC prints 768.7-.

273 Chapter 10 I BASIC Ke.ywords

fills leading spaces with asterisks. The 2 asterisks also establish 2 more positions in the field.

PRINT USING "**####"; 44.0 BASIC prints ****44 prints a dollar sign immediately before the number. This specifies 2 more digit positions, one of which is the dollar sign. You may not use exponent format with $$.

PRINT USING "$$##.##'I;112.7890 BASIC prints $112.79 fills leading spaces with asterisks and prints a dollar sign immediately before the number.

PRINT USING "**$##.##'I;8.333 BASIC prints """$8.33 prints a comma before every third digit to the left of the decimal point. The comma establishes another digit position. PRINT US I NG 1234.5 BASIC prints 1,234.50 prints in exponential format. The 4 exponent signs are placed after the digit position characters. You may specify any decimal point position. You may not use $$ with exponent format. PRINT US I NG ". 888888 BASIC prints .88893 + 06 Prints next character as a literal character

PRINT US I NG "-! ## . ##-! ";12.34 BASIC prints !1 2.3 4!

274 Chapter 10 1 BASIC Keywords

Sample Program

420 CLS: A$ = 'I**$##,######.##DOLLARS" 430 INPUT "WHAT IS YOUR FIRST NAME"; F$ 440 INPUT "WHAT IS YOUR MIDDLE NAME"; M$ 450 INPUT "WHAT IS YOUR LAST NAME". L$ 460 INPUT "ENTER AMOUNT PAYABLE"; b 470 CLS : PRINT "PAY TO THE ORDER OF 'I;

480 PRINT USING "!! !! 'I; FS; 'I."; MB; " 0,'I. 490 PRINT LF 500 PRINT :PRINT USING A$; P In Line 480, each ! picks up the first character of one of the fol- lowing strings (F$, ".", M$, and "." again). Notice the 2 spaces in "!!b!!b".These 2 spaces insert the appropriate spaces after the initials of the name (see below). Also notice the use of the vari- ables A$ for format and P for item list in Line 500. Any serious use of the PRINT USING statement would probably require the use of variables rather than constants, at least for data items. (We have used constants in our examples for the sake of better illustration.) When the program above is run, the display shows: WHAT IS YOUR FIRST NAME? JOHN WHAT IS YOUR MIDDLE NAME? PAUL WHAT IS YOUR LAST NAME? JONES ENTER AMOUNT PAYABLE? 12345.6 PAY TO THE ORDER OF J. P. JONES *****$12,345.60 DOLLARS

275 Chapter 10 I BASIC Keywords

PRINT# Statement

PRINT# buffr,[USINGformat] data[,data,...I

Writes data items to a sequential disk file. Buffer is the number assigned to the file when you opened it. When you first open a file for sequential output, BASIC sets a pointer to the beginning of the file-that is where PRINT# starts writing the data items. At the end of each PRINT# opera- tion, the pointer advances so that data items are written in sequence. A PRINT# statement creates a disk image similar to the image a PRINT to the display creates on the screen. For this reason, be sure to delimit the data so that it will be input correctly from the disk. PRINT# does not compress the data before writing it to disk. It writes an ASCII-coded image of the data. When you include the USING option, data is written to the disk in the format you specify. See PRINT USING. Examples If A = 123.45 PRINT# l,A writes this 9-byte character sequence to the file as: hl123.45hl carriage return The punctuation in the PRINT list is very important. Unquoted commas and semicolons have the same effect as they do in regu- lar PRINT statements to the display. For example:

A = 2300 B = 1.303 PRINT# 1, A,B writes the data on disk as: hl 2300 hlhlhlbhlbhlhlhlhl 1.303M carriage return

276 Chapter 10 I BASIC Keywords

The comma tells BASIC to tab between A and B, which creates 10 extra spaces in the file. Generally you do not want to use up storage space this way, so you use semicolons instead of commas.

PRINT# 1, A; ” , ‘I* This time BASIC writes the data as: 123.45,l .303 An INPUT# statement reads this as 2 separate fields. If string variables contain commas, semicolons, or leading blanks, enclose them in quotation marks. For example:

A$ = CAMERA, AUTOMATIC E$ = 102382 PRINT# 1, A$; E$ writes the data as: CAMERAMMM~MMMM~~AUTOMATICl82382 An INPUT# statement reads this as 2 separate fields

A$ = CAMERA E$ = AUTOMATIC182382 To separate these 2 strings properly in the file, write quotation marks using the hexadecimal representation CHR$(34). For example : PRINT# 1, CHR$(34); A$; CHR$(34); E$; CHRs(34) BASIC writes the following image to the file: “CAMERA, AUTOMATIC”1 02382” The statement INPUT# 1, A$, B$ reads “CAM- ERA,AUTOMATIC” into A$ and “102382” into B$.

277 Chapter 10 I BASIC Ke,ywords

You can write files in a carefully controlled format using PRINT# USING. You also can use this option to control how many characters of a value are written to disk.

For example, suppose A$ = “LUDWIG’, B$ = “VAN”, and C$ = “BEETHOVEN’. Then the statement: PRINT# 1, USING”!.! .\MM\“;A$;B$;C$ writes the data in nickname form: L . V. BEET (In this case, we did not want to add any explicit delimiters.) See PRINT USING for more information on the USING option.

278 Chapter 10 I BASIC Ke.ywords

PSET/PRESET/Graphics Statement

PSET [STEP] (x,y)[,colorl PRESET [STEP] (x,y)[,colorl

Draws a point on the display.

The STEP option tells BASIC that the (XJ) coordinates are rela- tive to the last point referenced.

(XJ) specify the coordinates in which to draw the point. X is the horizontal coordinate and y is the vertical coordinate. Color specifies the color of the point. See Chapter 8, “Displaying Color and Graphics” for information on coordinates and colors. The only difference between the PSET and PRESET statements is the default values for color. If you use PSET, color defaults to the foreground color. If you use PRESET, color defaults to the background color. Note: BASIC does not print and does not issue an er- ror message for points the coordinate values of which are beyond the edge of the screen. However, values outside the integer range (-32768 to 32767) cause an overflow error.

Sample Program 5 SCREEN 3 10 FOR 1=0 TO 100 20 PSET (1,I) 30 NEXT I’draw a diagonal line to (100,100) 40 FOR I = 100 TO 0 STEP -1 50 PRESET (1,1),0 60 NEXT I 70 ‘clear the line by setting each pixel to 0 80 SCREEN 0

Lines 10 to 30 draw a diagonal line on the screen from the home position to Position 100,100. Lines 40 to 60 erase the line by drawing another line at the same position in the background color.

279 Chapter 10 I BASIC Keywords

PUT Statement

PUT [#lbuffr[,recordl

Puts a record in a direct access disk file. Buffer is the number assigned to the file when you opened it. The number sign (#) is optional. It is provided for compatibility with other BASICs. Record is the record number you want to write to the file. It is an integer in the range 1 to 16,777,215. If you omit record, the current record number is used. If record is higher than the end-of-file record number, then rec- ord becomes the new end-of-file record number. The first time you use PUT after opening a file you must specify the record. The first time you access a file via a particular buffer the next record is set equal to one greater than the last record accessed. See Chapter 7, “Disk Files,” for programming information. Examples PUT 1 writes the next record from Buffer 1 to a direct access file. PUT 1 ,25 writes Record 25 from Buffer 1 to a direct access file.

280 Chapter 10 I BASIC Keywords

PUT/Communications Statement

PUT [ # 1 buffr, num ber

Transfers data from the communications buffer to the communi- cations line. Buffer is the number assigned to the file when you opened it. The number sign (#) is optional. It is provided for compatibility with other BASICs. Number is the number of bytes to transfer. It cannot exceed the value you used in the LEN option in the OPEN COM statement. Note: Because of the low performance associated with telephone line communications, we recommend that you not use GET and PUT statements in such applications.

Example PUT 2,80 transfers 80 bytes from communications buffer (Buffer 2) to the communications line.

Sample Program

10 OPEN "COM1 :I' AS 1 20 FIELD 1, 8 AS A$ 30 OPEN "R" ,3, "da t a . f i 1" ,8 40 FIELD 3, 8 AS NS 50 FOR I = 1 TO 7 60 GET 3, I 70 LSET A$=N$ 80 PUT 1 ,8 90 NEXT I 100 CLOSE This program moves the data from the data.fiZ file buffer to the communications buffer. Line 80 sends the data in the communi- cations buffer to the communications line.

281 Chapter 10 I BASIC Keywords

PUT/Graphics Statement

Transfers an image stored in an array onto the screen. You get the GET/Graphics and PUTiGraphics statements to- gether for animation and high-speed object motion in Screen Modes 1, 2, 3, or 4. The GET/Graphics statement transfers the screen image described by specified points of the rectangle in the array. The PUT/Graphics statement transfers the image from the array to the display. (x,y) specify the coordinates where the image begins. x is the horizontal coordinate and y is the vertical coordinate. The x and y coordinates specify the coordinate of the upper left corner of the image. If you omit x and y, BASIC begins the im- age at the last point referenced on the screen. See Chapter 8, “Displaying Color and Graphics” for information on coordinates for the current screen mode. BASIC returns an “Illegal function call” error if the image is too large to fit on the current viewport. Array is the array variable name that holds the image. Action sets the type of interaction between the transferred image and the image already on the screen. Action may be PSET, PRE- SET, AND, OR, or XOR. If you omit action, BASIC assumes XOR. The following describes each type of action: PSET transfers the data to the screen exactly as it was stored in the array.

282 Chapter 10 I BASIC Keywords

PRESET produces an opposite image on the screen. With 2 color sets, white becomes black on the screen. With 4 and 16 color sets, the color value becomes the numeric opposite on the screen. This table shows the color displayed for each possible value:

4 color 16 color Array Screen Array Screen Value Color Value Color 0 3 0 15 1 2 1 14 2 1 2 13 3 0 3 12 4 11 5 10 6 9 7 8 8 7 9 6 10 5 11 4 12 3 13 2 14 1 15 0 AND transfers the image over existing image. The result is a logical AND of the array and the image on the screen. OR superimposes an image onto an existing image. The re- sult is a logical OR of the array and the image on the screen. XOR inverts the points on the screen where a point exists in the array image. When an image is PUT against a com- plex background twice, the background is restored un- changed. This lets you move an object around the screen without obliterating the background.

283 Chapter 10 I BASIC Keywords

Animation To perform object animation, follow these steps: 1. Put the object on the screen using XOR. 2. Calculate the next position of the object. 3. Put the object on the screen a second time at the previous lo- cation to remove the previous image. 4. Repeat Step 1, putting the object at the next location. If you do movement this way, the background is not changed. You can reduce flicker by minimizing the time between Steps 4 and 1 and by ensuring enough time delay between Steps 1 and 3. If you are animating more than 1 object, process every object at the same time, 1 step at a time. If preserving the background is not important, you can perform animation using the PSET action rather than the XOR action. Leave a border around the image as large or larger than the maximum distance the object moves. When you move an object, this border effectively erases any points. This method may be faster than the XOR method described before, because only one PUT is required to move an object.

Sample Program See the GET/Graphics statement.

284 Chapter 10 I BASIC Ke.ywords

RANDOMIZE Function

RANDOMIZE [number]

Reseeds the random number generator. Number may be an integer, or single- or double precision num- ber. If you omit number, BASIC suspends program execution and prompts you for a number before executing RANDOMIZE: Random Number Seed (-32768 to 32767)7 If the random number generator is not reseeded, the RND func- tion returns the same sequence of numbers each time it is exe- cuted. To change the sequence of random numbers every time the RND function is executed, place a RANDOMIZE statement before the RND function. You can use the TIMER function to ensure that the random number generator is reseeded with a different value each time BASIC executes the RANDOMIZE function. For example, the statement: RANDOMIZE TIMER uses the value returned by TIMER as the seed. TIMER returns the number of seconds that have elapsed since midnight or the last system reset. Because the seconds are constantly changing, number has a different value each time BASIC executes this stat ement . Sample Program 10 CLS 20 RANDOMIZE TIMER 30 INPUT "PICK A NUMBER BETWEEN 1 AND 100"; A 40 B = INT

285 Chawter 10 I BASIC Keywords

READ Statement

READ variable[,uariable,...I

Reads values from a DATA statement and assigns them to variables. BASIC assigns values from the DATA statement on a one-to-one basis. The first time READ is executed, the first value in the first DATA statement is assigned to the first variable; the second time, the second value is assigned to the second variable, and so on. A single READ may access 1 or more DATA statements, or sev- eral READS may access the same DATA statement. If a program contains multiple DATA statements, BASIC reads them in the or- der they appear. The values read must agree with the variable types specified in a list of variables; otherwise, a “Syntax error” occurs. If the number of variables in the READ statement exceeds the number of elements in the DATA statement(s1, BASIC returns an “Out of DATA” error message. If the number of variables speci- fied is less than the number of elements in the DATA state- ment(s), the next READ statements begin reading data at the first unread element. To reread DATA statements from the start, use the RESTORE statement.

Example READ T reads a numeric value from a DATA statement and assigns it to variable T.

286 Chawter 10 I BASIC Kevwords

Sample Program This program illustrates a common application for the READ and DATA statements. 40 PRINT "NAME", "AGE" 50 READ N$ 60 IF N$="END" THEN PRINT "END OF LIST": END 70 READ AGE 80 IF AGE<18 THEN PRINT N$, AGE 90 GOT0 50 100 DATFI "SMITH, JOHN", 30, "ANDERS, T.M." 20 110 DATA "JONES, BILL", 15, "DOE, SALLY", ;1 120 DATA "COLLINS, W.P.", 17, "END"

287 Chapter 10 I BASIC Kevwords

Statement

REM

Inserts a remark line in a program. REM instructs the computer to ignore the rest of the program line, which lets you insert remarks in your program for docu- mentation. Thus, when you look at a listing of your program, you can quickly interpret it. If REM is used in a multistatement program line, it must be the last statement in the line. You may use an apostrophe ('1 as an abbreviation for REM. Sample Program 110 DIM V<20) 120 REM CALCULATE AVERAGE VELOCITY 130 FOR 1=1 TO 20 140 SUM=SUM + VCI) 150 NEXT I OR 110 DIM V(20) 120 FOR 1=1 TO 20 'CALCULATE AVERAGE VELOCITY 130 SUM=SUM + V

288 ChaDter 10 I BASIC Kevwords

RENUM Statement

RE NUM [new Line1 [ [Iinel [ increment1I

Renumbers the program currently in memory. You can renumber the entire program or renumber from a specific line to the end. Line is the line in the program where BASIC starts renumber- ing. If you omit line, it renumbers the entire program. New line is the new line number assigned to line. If you omit new line, BASIC starts numbering at Line 10. Increment tells BASIC how to number the successive line. If you omit increment, it increments by 10. RENUM also changes all line number references appearing after GOTO, GOSUB, THEN, ON/GOTO, ONiGOSUB, ON ERROR GOTO, RESUME, and ERL. You cannot use RENUM to change the order of program lines. For example, if a program has lines numbered 10, 20, and 30, the command RENUM 15,30 is illegal, since this would place Line 30 before Line 20. Also RENUM cannot create line numbers greater than 65529. If you attempt to do this, BASIC returns an “Illegal function call” error and leaves the program unchanged. If BASIC finds an undefined line number within the program, it prints a warning message, “Undefined line xxxx in yyyy,” where xxxx is the undefined line number and yyyy is the line where it appears. RENUM renumbers the program despite this warning message. It does not change the incorrect line number reference, but it does renumber yyyy.

289 Chapter 10 I BASIC Keywords

Examples RENUM renumbers the entire program, using an increment of 10. The new number of the first line is 10. RENUM 600, 5000, 100 renumbers from Line 5000 to the end of the program. The first renumbered line becomes 600, and an increment of 100 is used between subsequent lines. RENUM 100,, 100 renumbers the entire program, starting with a new line number 100, and incrementing by 100s. Notice that the commas must be retained even though the middle argument is not used.

290 Chapter 10 I BASIC Ke-ywords

RESET Statement

RESET

Closes all open files on all drives. If a disk contains any open files, RESET writes all blocks in memory to disk. RESET ensures that all files on all diskettes are closed before you remove them from the drives. RESET is the same as a CLOSE statement for each open file.

291 Chapter 10 I BASIC Keywords

RESTORE Statement

RESTORE [Line]

Restores a program’s access to previously read DATA statements. Line is a line number that contains a DATA statement. If you specify line, the next READ statement accesses the first item in the specified DATA statement. If you omit line, BASIC resets to the first DATA statement in the program. This lets your program reuse the same DATA lines.

Sample Program 160 RECID X$ 170 RESTORE 180 READ Y$ 190 PRINT XS, Y$ 200 DCITFI FIRST ITEM, SECOND ITEM When you run this program, BASIC prints: FIRST ITEM FIRST ITEM Because of the RESTORE statement in Line 170, the second READ statement starts over with the first DATA item.

292 Chapter 10 I BASIC Ke.ywords

RESUME Statement

RESUME [line] RESUME NEXT

Resumes program execution after an error-handling routine. RESUME without an argument and RESUME 0 both cause the computer to return to the statement in which the error has occurred. RESUME line causes the computer to branch to the specified line number. RESUME NEXT causes the computer to branch to the state- ment following the point at which the error has occurred.

Examples RESUME If an error has occurred, this line transfers program control to the statement in which it has occurred. RESUME 10 If an error has occurred, transfers control to Line 10.

Sample Program 10 ON ERROR GOT0 900

900 IF

293 Chapter 10 I BASIC Keywords

RETURN Statement

RETURN [Line]

Returns control to the line immediately following the most re- cently executed GOSUB. Line tells BASIC to return to a specific line in the program. If you omit line, BASIC goes to the line immediately following the GOSUB. Use caution when specifying a line number with RETURN. Any other GOSUB, WHILE, or FOR statement remains active while a GOSUB subroutine is executing. If BASIC returns to a line number that is outside these loops, an error occurs because the loops were left incomplete. If the program encounters a RETURN statement without execu- tion of a matching GOSUB, an error occurs. Example RETURN 40 returns from the subroutine to Line 40 in the program.

Sample Program 330 PRINT "THIS PROGRAM FINDS THE AREA OF A CIRCLE" 340 INPUT "TYPE IN FI VALUE FOR THE RADIUS"; R 350 GOSUB 370 360 PRINT "AREA IS" ; A: END 370 A = 3.14 R * R 380 RETURN

294 Chapter 10 I BASIC Keywords

RIGHT$ Function

RIGHT$(string,nurnber)

Returns the specified number of characters from the far right portion of string. Number is an integer in the range 1 to 255. If number is equal to or greater than the length of string, BASIC returns the entire string.

Examples PRINT RIGHT$("WATERMELON", 5) prints MELON. PRINT RIGHT$("MILKY WAY", 25) prints MILKY WAY.

Sample Program 850 RESTORE : ON ERROR GOTO 880 860 READ COMPANY$ 870 PRINT RIGHT$CCOMPANY$, 21, : GOTO 860 880 END 890 DATA "BECHMAN LUMBER COMPANY, SEATTLE, WA" 900 DATA "ED NORTON SEWER SERVICE, BROOKLYN, NY"

910 DATA "HAMMON MANUFACTURING COMPANY ~ HAMMOND, IN" This program prints the name of the state in which each com- pany is located.

295 Chapter 10 I BASIC Keywords

RMDIR Statement

RMDIR dirpath

Removes (deletes) the directory specified by dirpath. Dirpath is a standard directory specification as described in Chapter 1. If you omit the drive identifier, the directory is de- leted from the current drive. If you omit the root directory sym- bol ( \ 1, the directory is deleted from the current directory. The directory being deleted must be empty except for the "." and ".." symbols. Use the MS-DOS COPY command to move those files you want to save; then use KILL to remove all files from the directory. Examples RMDIR "A: \ACCTS\PAYABLE" removes the directory PAYABLE from the ACCTS directory on Drive A. RMDIR "\ADDRESS" removes the directory ADDRESS from the root directory on the current drive. RMDI R "NAMES" removes the directory NAMES from the current directory on the current drive.

296 Chapter 10 I BASIC Keywords

RND Function

RND[(nurnber)]

Returns a random number in the range 0 and 1. BASIC uses the current seed when generating a random number and produces the same sequence of random numbers each time the program is run unless you reseed the random number gener- ator. Use the RANDOMIZE statement to reseed the random number generator If number is negative, RND starts the sequence of random num- bers at the beginning. If number is 0, RND repeats the last number generated. If you omit number or specify a positive value, RND returns the next number in the sequence. Example PRINT RND(1 1 prints the next decimal fraction in the sequence.

Sample Program 10 FOR I = 1 TO 5 20 PRINT INT(RND*l00); 30 NEXT I This program produces 5 random integers. Line 20 converts the decimal fraction returned by RND to a real number and trun- cates the real number to an integer.

297 Chapter 10 I BASIC Keywords

RSET Statement

RSET field name = data

Sets data in a direct access buffer field name in preparation for a PUT statement. Field name is a string variable defined in a FIELD statement. This statement is similar to LSET. The difference is that with RSET, data is right-justified in the buffer. See LSET for details.

298 Chapter 10 I BASIC Ke.ywords

RUN Statement

RUN [line] RUN pathmme[,R]

Executes a program. Line is the program line where BASIC begins execution. If you omit line, BASIC executes the program from the beginning. Pathnume specifies the disk file for BASIC to load into memory and execute. If you specify the R option, BASIC does not close the open files before loading the new program into memory. If you omit the R option, BASIC closes all open files before loading the program. RUN automatically clears all variables. Ex ample s RUN starts execution at the beginning of the program. RUN 100 starts execution at Line 100.

RUN " p r o g ram. a" loads and executes pr0gram.a. RUN "\WORD\editdata", R loads and executes editdata from the WORD directory without closing any open files.

299 ChaDter 10 I BASIC Kevwords

SAVE Statement

SAVE pathname [,AI SAVE pathname [,PI

Saves a program on disk with the specified name. Pathname is a standard file specification as described in Chapter 1. When you save a file to disk, you must specify the filename. If the file already exists on disk, its contents are lost when the file is re-created. The A option tells BASIC to save the program in ASCII format. If you omit the A option, BASIC saves the file in a compressed format. The compressed format takes less disk space than ASCII format. Also BASIC can save and load in compressed format faster than in ASCII format. BASIC programs are stored in RAM using compressed format. Use the ASCII format if you plan to use the MERGE command to merge the program with another. Also, data programs that be read by other programs usually must be in ASCII. When using the ASCII option, be sure your program has no embedded line feeds; otherwise, the computer will not be able to read it properly. Embedded line feeds are produced by typing [CTRL][T]in a program line. For compressed-format programs, a useful convention is the ex- tension .bas. For ASCII-format programs, use .txt. The P option protects the file by saving it in an encoded binary format. When a protected file is later run (or loaded), any at- tempt to list or edit it fails. The only operations that you can perform on a protected file are RUN, LOAD, and CHAIN.

300 \

Chapter 10 I BASIC Ke.ywords

Examples SAVE "A: f i le1 .bas" saves the resident program in compressed format as filel.bas. The file is placed on Drive A: in the current directory. SAVE "\EDUC\mathpak. txt", A saves the resident program in ASCII form, using the name math- pak.txt, on the current drive in the directory EDUC.

301 Chapter 10 I BASIC Ke,ywords

SCREEN Function

SCREEN (row,column, [ num ber])

Returns the ASCII code for the character at the specified row and column. Row is an integer in the range 1 to 25. Column is an integer in the range 1 to 80. Column must be in the range for the current screen mode. Number is applicable only for text mode. If you specify a non-zero number, SCREEN returns the color attribute, rather than the ASCII code, of the character. The attribute is in the range of 0 to 255, and can be translated as follows: attribute MOD 16 = foreground color (((attribute - foreground)/ 16)MOD 128) = background color (number>l27) is true (-1)if the character is blinking and false (0)if it is not. In the graphics modes, if the location does not contain a stan- dard ASCII character, BASIC returns a value of zero.

Sample Program 10 LOCQTE 20,20 20 PRINT “ROBBIE” 30 A = SCREEN(20,20):B = SCREEN(20,2l) 40 PRINT A,B Line 10 positions the cursor to Row 20, Column 20. Line 20 prints the message at the current cursor position. Line 30 stores the ASCII code for “R’ in the variable A and the ASCII code for “0”in variable B. Line 40 prints: 82 79

302 Chapter 10 I BASIC Ke.ywords

SCREEN Statement

SCREEN [model[,[burst][, [active pagel[,dispZay page11 [,erasell

Sets the screen attributes to be used by all other graphics state- ments (CIRCLE, LINE, DRAW, POINT, PSET, PRESET, PAL- ETTE, and PALETTE USING). Mode is an integer in the range 0 to 6 that sets the valid coordi- nates and the number of colors you can use. Screen Mode de- scriptions are given in Chapter 8, “Displaying Color and Graphics.” When you change from one mode to another, BASIC stores the new screen mode, erases the video display, and sets the fore- ground color to white and the background and border colors to black. Burst enables or disables color. In Screen Mode 0 (text mode), set burst to 0 to disable color or 1 to enable color. In medium resolu- tion (Screen Modes 1 and 4), set burst to 0 to enable color or 1 to disable color. Burst has no effect in high and low resolution (Screen Modes 3, 5, and 6) where color is always enabled or in Screen Mode 2, which is black and white. Active page is an integer that selects the video page to which BASIC will write. All output statements to the screen go to the selected active page. The range depends on the screen mode and the amount of video memory available. If you omit active page, BASIC assumes the current active page. Active page is initially set to Page 0. Display page is an integer that selects the video page for BASIC to display. The range is the same as active page. If you omit dis- play page, BASIC uses the same page as active page. BASIC au- tomatically sets display page to active page if the program halts because of an END or STOP statement or because of an error. All video pages share one cursor. Therefore, when switching ac- tive pages, you should save the cursor position with the POS and CSRLIN statements. Then when you return to an active page, you can restore the cursor with the LOCATE statement.

303 Chapter 10 I BASIC Ke.ywords

Erase is an integer in the range 0 to 2 that tells BASIC how much video memory to erase. Erase can be one of the following: 0 Do not erase video memory, even if the screen mode changes. 1 Erase the union of the new page and old page if mode or burst change. 2 Erase all video memory if mode or burst changes. If you omit erase, BASIC assumes 1. If you omit any parameters (except display page), BASIC uses the previous values. For more information on the graphics statements and video pages, see CLEAR and Chapter 8, “Displaying Color and Graphics.” Examples 10 SCREEN 0,0 selects text mode with color off. 60 SCREEN 2 changes to high resolution, 2-color, graphics mode.

304 Chapter 10 I BASIC Keywords

SGN Function

SGN( num her)

Determines number's sign. If number is a negative number, SGN returns -1. If number is a positive number, SGN returns 1. If number is zero, SGN returns 0. Examples Y = SGN

305 Chapter 10 I BASIC Keywords

SHELL Advanced Statement

SHELL [command]

Loads and executes another program (.EXE or .COW or an in- ternal command as a child process to the original program. After the child process ends, control returns to the BASIC pro- gram at the statement following the SHELL statement. Command is a string expression containing the name of the pro- gram you want to run. You may also specify command argu- ments on the command line. Use a space to separate arguments from the program name. If you omit command, SHELL transfers control to COMMAND. You can now execute MS-DOS commands as allowed by COMMAND. To return to BASIC, use the MS- DOS EXIT command. SHELL sends the command information to COMMAND.COM, the MS-DOS command processor. If you omit the extension in the program name, COMMAND looks for the program with a .COM extension, then with an .EXE extension and finally with a .BAT extension. If COMMAND still cannot find the program, it issues a “File not found” error to SHELL. Note: Do not specify BASIC as the command string of SHELL. If you do, BASIC might not function properly. For more information on child processes and COMMAND.COM, see the MS-DOS Reference and the Programmer’s Reference man- uals for your computer. They are available through your Radio Shack Computer Store.

306 Chapter 10 I BASIC Keywords

Examples SHELL transfers control to COMMAND.COM. You can execute MS-DOS commands such as: DIR TINE and then type EXIT to return to BASIC. The following command uses redirection of input and output and the MS-DOS SORT command. SHELL"S0RT data.out" sorts the text from data.in and writes it to data.out.

307 Chapter 10 I BASIC Ke.ywords

SIN Function

SIN(number)

Returns the sine of number SIN returns the angle (in radians) whose cosine is number. Number must be in radians. To obtain the sine of number when number is in degrees, use SIN(number * PI/180), where PI equals 3.141593. BASIC always returns the result as a single precision number unless you set the /D switch when starting up BASIC. Examples PRINT SINC7.96) prints .9943854. Sample Program 660 INPUT "FINGLE IN DEGREES"; A 670 PRINT "SINE IS"; SIN

308 Chapter 10 I BASIC Keywords

SOUND Statement

SOUND frequency, duration[,[uolumel [,[voice111 SOUND ON SOUND OFF

Generates a sound with the frequency and duration specified. When a SOUND statement is producing sound, the program con- tinues to execute. See the PLAY statement for more information about executing program lines during SOUND. frequency specifies the desired tone in Hertz, and is an integer in the range 1 to 32767. The lowest frequency the multi-voice sound chip can produce is 110 Hz. Any value below 110 Hz sounds at 110 Hz. The frequency 32767 is treated as the silence frequency. To create periods of silence, use SOUND 32767, duration. Possible frequencies are given later. Duration is an integer in the range 1 to 65535, specifying the duration in clock ticks. Clock ticks occur 18.2 times per second. The shortest sound is 1, and the longest is 65535. If duration is 0, BASIC turns off any currently running SOUND statement. Otherwise, BASIC completes the first SOUND statement before executing the next one. Volume is an integer in the range 0 to 15, where 0 is the lowest volume and 15 is the highest volume. If you omit uolurne, BASIC uses 8. You must execute a SOUND ON statement to use uolurne. Voice is an integer in the range 0 to 2. If you omit voice, BASIC uses 0. You must execute a SOUND ON statement to use voice. You can set each voice to a different tone to produce a 3-note chord. SOUND ON enables the external speaker that supports multi- voice sounds using the PLAY or SOUND statements. SOUND OFF disables the external speaker. You can use SOUND with BEEP to direct sound to either the computer’s speaker or external speaker. See also BEEP for the results of the different combinations of BEEP and SOUND.

309 Chapter 10 i BASIC Keywords

This statement can be especially useful in educational applica- tions. For example, you can have the computer respond with a sound if a user has answered a program’s prompt incorrectly (or vice versa). You can use the SOUND or PLAY statements to generate musi- cal notes from your computer. This chart shows the frequency you specify to generate the notes in the octave above middle C. Middle C is the first note in the chart. Note Frequency C 523.25 D 587.33 E 659.26 F 698.46 G 783.99 A 880.00 B 987.77 C 1046.50 To generate notes in the octave below middle C, find the fre- quency of the note’s letter in the chart and divide that number by 2. For example, the note A in the octave below middle C has a frequency of 440.00 To generate notes in the octave above middle C, find the fre- quency of the note’s letter in the chart and multiply that number by 2. For example, the note A in the octave above middle C has a frequency of 1760.00 There are 1092 clock ticks per minute. To determine the number of clock ticks for 1 beat, divide the beats per minute into 1092. The chart below shows the number of clock ticks for some typical tempos. Beats Ticks Tempo per minute per minutes Largo 40- 60 27.3 -18.2 Larghetto 60- 66 18.2 -16.55 Adagio 66- 76 16.55-14.37 Andante 76-108 14.37-10.11 Moderato 108-120 10.11- 9.1 Allegro 120-168 9.1 - 6.5 Presto 168-208 6.5 - 5.25

310 Chapter 10 I BASIC Keywords

Sample Program 5 SOUND ON 10 INPUT "IN HONOR OF WHOM WAS THE CONTINENT OF AMERICA NAMED"; A$ 20 IF A$="AMERIGO VESPUCCI" THEN SOUND 500,50 ELSE GOT0 40 30 PRINT "THAT'S RIGHT!": END 40 SOUND 37,2 : PRINT "THE CORRECT ANSWER IS AMER I GO VESPUCC I "

311 Chapter 10 I BASIC Keywords

SPACE$ Function

SPACE $( num ber)

Returns a string of number spaces. Number must be in the range 0 to 255.

Example

PR INT "DESCR IPT I ON" SPFICE $ ( 4 1 "TYPE" SPACE $ (9 1 "QUANTITY" prints DESCRIPTION, 4 spaces, TYPE, 9 spaces, QUANTITY.

Sample Program 920 PRINT "Here" 930 PRINT SP&CE$C13) "i5" 940 PRINT SPFICESC26) "an" 950 PRINT SPACES(39) "example" 960 PR.INT SPACE$

312 Chapter 10 I BASIC Keywords

SPC Function

SPC(number)

Skips number spaces in a PRINT statement. Number is in the range 0 to 255. A semicolon is assumed to fol- low the SPC(number) command. You may use SPC only with PRINT, LPRINT, or PRINT# . See also SPACE$.

Example PRINT "HELLO" SPC( 15) "THERE" prints: HELLO THERE

313 Chapter 10 I BASIC Ke.ywords

SQR Function SQR(number)

Returns the square root of number. Number must be greater than zero. BASIC always returns the result as a single precision number unless you specified the /D switch when starting up BASIC.

Example PRINT SQR(155.7) prints 12.47798.

Sample Program 680 INPUT "TOTAL RESISTANCE (OHMS)"; R 690 INPUT "TOTAL REACTANCE (OHMS)"; X 700 2 = SQR((R * R) + (X * XI) 710 PRINT "TOTAL IMPEDANCE (OHMS) IS" 2 This program computes the total impedance for series circuits.

314 Chapter 10 I BASIC Keywords

STICK Function

STICK (action)

Returns the coordinates of the joysticks. Action may be one of the following: 0 reads all 4 coordinates, and returns the horizontal (x) coordinate for Joystick A. 1 returns the vertical (y) coordinate for Joystick A. 2 returns the horizontal (x) coordinate for Joystick B. 3 returns the vertical (y) coordinate for Joystick B. The coordinates returned by STICK(l), STICK(2), and STICK(3) are those previously read by STICK(0). Joystick A is the left joystick and Joystick B is the right joystick.

Sample Program The following program continually displays the coordinates of joystick B. 10 CLS 20 LOCATE 1 ,I 25 T=STICK<0) 30 PR I NT"B: "; STI CK(2) 4 0 P R I NT"B : " ;ST I C K ( 3 1 50 GOT0 20

315 Chapter 10 I BASIC Keywords

STOP Statement

Stops program execution. When BASIC encounters a STOP statement, it prints the mes- sage “BREAK IN xax,” where xxxx is the line number that con- tains the STOP. STOP is primarily a debugging tool. During the break in execution, you can examine variables or change their values. Use the CONT statement if you want to resume execution. If the program itself has been altered during the break, you cannot use CONT. Unlike the END statement, STOP does not close files.

Sample Program 2260 X = RNDCl0) 2270 STOP 2280 GOT0 2260 A random number in the range 1 to 10 is assigned to X and then program execution halts at Line 2270. You can now exam- ine the value X with PRINT X. Type CONT to start the cycle again.

316 Chapter 10 I BASIC Keywords

STR$ Function

STR$(number)

Converts number to a string. If number is positive, STR$ places a blank before the string. If number is negative, STR$ places a minus sign (-1 before the string. While arithmetic operations may be performed on number, only string functions and operations may be performed on the string. The complementary function to STR$ is VAL.

Example S$ = STR$

Sample Program

10 A = 1 .6 : B# = A : C# = VAL(STR$(A)) 20 PRINT "REGULAR CONVERSION" TAB(40) "SPEC IAL CONVERSION" 30 PRINT B# TAB(40) C#

317 Chapter 10 I BASIC Ke.ywords

STRIG Statemen t STRIG ON STRIG OFF

Enables the STRIG function.

STRIG ON STRIG ON lets you execute STRIG function statements to return the status of the joystick buttons. If you attempt to execute a STRIG function before you execute a STRIG ON statement, BASIC issues an “Illegal function call” error.

STRIG OFF If you execute a STRIG OFF statement, you can not execute STRIG function. Executing a STRIG function after a STRIG OFF statement results in an “Illegal function call” error. When you load BASIC, the default is STRIG OFF and you cannot execute STRIG/Function statements. You cannot place a STRIG function in a subroutine that you branch to as a result of an ON STRIGO GOSUB statement. BASIC does not keep track of which button was pressed after the ON STRIG() GOSUB statement is executed. If you wish to trap both buttons and perform a different procedure for each button, you must execute a STRIG/Trap for each button, and you must branch to different subroutines with different ON STRIGO GO- SUB statements. See STRIG Function, STRIG/Trap, and ON STRIGO GOSUB for additional information on joystick trapping.

318 Chapter 10 I BASIC Keywords

STRIG Function

STRIG(number)

Returns the status of joystick buttons. Number is an integer in the range 0 to 7 to test the status of the joystick buttons. Variable is a numeric variable to receive the value returned by number . Each number tests for a different status of the buttons and re- turns a numeric value in variable regarding the results of the test. The numbers and their functions are: Tests to see if Trigger A1 has been pressed and re- leased since the last STRIG(0) function was executed. BASIC returns a -1 if it has been pressed and a 0 if not. Tests to see if you are currently pressing Trigger Al. BASIC returns a -1 if you are pressing it and a 0 if not. Tests to see if Trigger B1 has been pressed and re- leased since the last STRIG(2) function was executed. BASIC returns a -1 if it has been pressed and a 0 if not. Tests to see if you are currently pressing Trigger B1. BASIC returns a -1 if you are pressing it and a 0 if not. Tests to see if Trigger A2 has been pressed and re- leased since the last STRIG(4) function was executed. BASIC returns a -1 if it has been pressed and a 0 if not. Tests to see if you are currently pressing Trigger A2. BASIC returns a -1 if you are pressing it and a 0 if not.

319 Chapter 10 I BASIC Keywords

6 Tests to see if Trigger B2 has been pressed and re- leased since the last STRIG(6) function was executed. BASIC returns a -1 if it has been pressed and a 0 if not. 7 Tests to see if you are currently pressing Trigger B2. BASIC returns a -1 if you are pressing it and a 0 if not. Joystick A is the left joystick and Joystick B is the right joystick. You must execute a STRIG ON statement before you can execute a STRIG function. If you attempt to execute a STRIG function before you execute a STRIG ON, BASIC issues an “Illegal func- tion call” error. See STRIG/Trap. You cannot place a STRIG function in a subroutine that you branch to as a result of an ON STRIGO GOSUB statement. BASIC does not keep track of which button was pressed after the ON STRIG() GOSUB statement is executed. If you wish to trap both buttons and perform a different procedure for each button, you must execute a STRIGiTrap for each button, and you must branch to different subroutines with different ON STRIGO GO- SUB statements.

Sample Program This program tells BASIC to beep whenever the trigger on Joys- tick A is pressed. 10 STRIG ON 20 IF STRIG(0) THEN BEEP 30 GOT0 20

320 Chapter 10 I BASIC Keywords

STRIG/Trap Statement

STRIG(number) ON STRIG(number) OFF STRIG(number) STOP

Turns on, turns off, or temporarily halts joystick trapping. Number is a value of 0, 2, 4, or 6 to indicate the joystick button you are trapping: 0 indicates Trigger Al. 2 indicates Trigger B1. 4 indicates Trigger A2. 6 indicates Trigger B2. Joystick A is the left joystick and Joystick B is the right joystick.

STRIGO ON STRIGO ON enables joystick trapping with the ON STRIGO GOSUB statement. If you execute a STRIGO ON statement, BASIC checks after every program statement to see if you pressed a joystick button. If you press a joystick button, BASIC transfers program control to the line number specified in the ON STRIGO GOSUB statement. See ON STRIGO GOSUB. Note: Do not confuse the STRIG/Trap statement with the STRIG function statement. These are 2 separate statements that perform 2 distinct functions in BASIC.

STRIGO STOP STRIG() STOP temporarily halts joystick trapping. If you press a joystick button after a STRIGO STOP statement is executed, BASIC does not transfer program control to the subroutine until trapping is turned on again with a STRIGO ON statement. BASIC remembers that the joystick buttons were pressed and transfers program control to the subroutine immediately after joystick trapping is turned on again.

321 Chapter 10 I BASIC Keywords

STRIG OFF STRIGO OFF turns off joystick trapping with the ON STRIGO GOSUB statement. When you load BASIC, STRIGO OFF is the default, because joy- stick trapping slows program execution. Therefore, if you execute a STRIGO ON statement to enable joystick button trapping, we recommend that you also execute a STRIGO OFF statement when you no longer need to check for joystick button activity. If you press a joystick button after a STRIG() OFF statement is executed, BASIC does not remember that the joystick buttons were pressed when joystick trapping is turned on again.

Example See STRIG.

322 Chapter 10 I BASIC Keywords

STRING$ Function

STRING$(number,character)

Returns a string containing the specified number of character. Number must be in the range 0 to 255. Character is a string or an ASCII code. If you use a string con- stant, you must enclose it in quotation marks. All the characters in the string have either the ASCII code, or the first letter of the string specified. STRING$ is useful for creating graphs or tables.

Examples: B$ = STRINGSC25, “X”) puts a string of 25 “X”s into B$. PRINT STRING$(50, 10) prints 50 blank lines on the display, because 10 is the ASCII code for a line feed.

Sample Program 1040 CLEAR 300 1050 INPUT “TYPE IN 3 NUMBERS BETWEEN 33 AND 159”; N1 , N2, N3 1060 CLS: FOR I = 1 TO 4: PRINT STRING$(20, Nl): NEXT I 1070 FOR J = 1 TO 2: PRINT STRINGs(40, N2): NEXT J 1080 PRINT STRINGB(80, N3) This program prints 3 strings. Each string has the character corresponding to one of the ASCII codes provided.

323 Chapter 10 I BASIC Keywords

Statement

SWAP varia blel paria ble2

Exchanges the values of 2 variables. You may swap variables of any type (integer, single precision, double precision, or string). However, both must be of the same type; otherwise, a "Type mismatch" error results. Either or both variables may be elements of arrays. If one or both of the variables are non-array variables that have not been assigned values, an "Illegal function call" error results.

Example SWAP F1#, F2# swaps the values of F1# and F2#. The contents of F2# are put into F1#, and the contents of F1# are put into F2#. Sample Program

10 A$="ONE ":B$="ALL ":C$="FOR " 20 PRINT A$ C$ E$ 30 SWAP AS, E$ 40 PRINT A$ C$ E$ When run, the program displays: ONE FOR ALL ALL FOR ONE

324 Chapter 10 I BASIC Ke.ywords

SYSTEM Statement

SYSTEM

Returns you to the MS-DOS command level. BASIC closes all files before returning to MS-DOS. Your resident BASIC program is not retained in memory. Examples SYSTEM returns you to MS-DOS. Your resident BASIC program is lost.

325 Chapter 10 I BASIC Keywords

TAB Function

TAB (number)

Spaces to position number on the display. Number must be in the range 1 to 255 and specifies the charac- ter position to which to tab. The leftmost position is 1, and the rightmost position is the set width minus 1 (WIDTH-1). If the current print position is already beyond space number, TAB goes to that position on the next line. You cannot use TAB to move the cursor to the left. You cannot use TAB more than once in a print list. You may use TAB only with the PRINT and LPRINT statements.

Sample Program 1 0 PRINT "NAME" TAB(25) "AMOUNT": PRINT 20 READ A$, B$ 30 PRINT A$ TABC25) BS 40 DATA "G.T. JONES","$25.00" When you run this program, the display shows: NAME AMOUNT G. T. JONES $25.00

326 Chapter 10 I BASIC Ke.ywords

TAN Function

TAN(num ber)

Returns the tangent of number. Return the angle (in radians) whose arc tangent is number. Number must be in radians. To obtain the tangent of number when it is in degrees, use TAN (number * PI/180), where PI equals 3.141593. BASIC always returns the result as a single precision number unless you set the /D switch when starting up BASIC.

Example PRINT TAN(7.96) prints -9.396959.

Sample Program This programs asks you to input an angle in degrees and re- turns the tangent in radians. 720 INPUT "ANGLE IN DEGREES". ANGLE 730 T = TANCCINGLE * .01745324) 740 PRINT "TAN IS" T

327 Chapter 10 I BASIC Keywords

TIME$ Function

TIME$[ = string]

Sets or retrieves the current time. String is a literal, enclosed in quotation marks, that sets the time by assigning its value to TIME$. If you omit string, BASIC retrieves the current time. BASIC uses a 24-hour clock. For example, it sets 8:15 P.M. as 20:15:00.

Setting the Time You set the time in the following format: hh:mm:ss The hours (hh)may be any number 0-23. The minutes (mm)and the seconds (ss) may be any number 0 through 59. If you omit the minutes, minutes and seconds default to zero. If you omit the seconds, seconds default to zero. Although you may omit leading zeros in each of the values, you must include at least 1 digit of the preceding value. For example, you may type 1:5 to set the the time to 1:05 A.M. However, :5 is invalid.

Retrieving the Time BASIC always returns the time in the 8-character (hh:mm:ss) format, with leading zeros. You may set the time before you enter BASIC. If you do not set the time at the MS-DOS time prompt or with the TIME$ statement, BASIC returns the length of the time that has elapsed since you turned on the computer.

328 Chapter 10 I BASIC Keywords

Examples TIMES ="14:15" sets the current time to 14:15:00. TIMES = "3:3:3" sets the current time to 03:03:03. FIS =T I MES assigns the current time to the variable A$. PRINT TIMES prints the current time.

329 Chapter 10 I BASIC Keywords

TIMER Function TIMER

Returns the number of seconds since midnight or since the last system reset. BASIC always returns a single precision number. You can use TIMER as the argument for the RANDOMIZE statement to reseed the random number generator. See RAN- DOMIZE for more information. Example A = TIMER stores the number returned by TIMER into variable A.

330 Chawter 10 I BASIC Kevwords

TIME R/Trap Statement

TIMER action

Turns on, turns off, or temporarily halts timer event trapping. Action may be any of the following: ON enables timer event trapping. OFF disables timer event trapping. STOP temporarily suspends timer event trapping. The TIMER ON statement turns on the trap. BASIC checks the the value of timer after each program line. If the number is equal to that in the ON TIMERO GOSUB statement, BASIC transfers program control to the line number specified. The TIMER STOP statement temporarily halts timer trapping. If the timer equals the specified number, BASIC does not trans- fer program control to the ON TIMERO GOSUB statement until you turn on trapping again by executing a TIMER ON state- ment. BASIC remembers that the timer value was equal and branches to the subroutine immediately after trapping is turned on again. The TIMER OFF statement turns off timer trapping. BASIC does not remember if the value of timer equals the number spec- ified when trapping is turned on again.

Sample Program See ON TIMERO GOSUB for an example.

331 Chapter 10 I BASIC Keywords

TROFF, TRON Statements

TROFF TRON

Turn the trace function on/off. TRON turns on the tracer and TROFF turns it off. The tracer lets you follow program flow. This is helpful for de- bugging and for analyzing the execution of a program. After a program is debugged, you can remove the TRON and TROFF statements. Each time the program advances to a new line, the tracer dis- plays that line number inside a pair of brackets.

Sample Program 2290 TRON 2300 X = X * 3.14159 2310 TROFF Lines 2290 and 2310 assure you that Line 2300 is actually being executed, because [23001 is printed on the display each time it is executed. 5 TRON 10 K=10 20 FOR J=l TO 2 30 L=K+10 40 PRINT J;K;L 50 K=K+10 60 NEXT J 70 TROFF 80 END When you run this program, BASIC prints: [101[201[301~4011 10 20 ~501~601[301[4012 20 30 [501[601[701

332 Chapter 10 I BASIC Keywords

USR Function

USR[ nu m ber](argument)

Calls a user’s assembly-language subroutine identified with number and passes argument to that subroutine. The number you specify must be the same as the corresponding DEF USR statement for that routine. If you omit number, BASIC assumes zero. USR lets you call as many as 10 assembly-language subroutines and then continue execution of your BASIC program. Before you can execute a USR function call, you must define the subroutine’s address in a DEF SEG and DEF USR statement. The DEF SEG defines the address of the segment containing the subroutine. The DEF USR statement defines the subroutine being called and its offset from the beginning of the segment set by DEF SEG. See DEF SEG, DEF USR, and the section “Inter- facing With Assembly-Language Subroutines” in Chapter 11.

333 Chapter 10 I BASIC Ke-ywords

VAL Function VAL(string)

Calculates the numerical value of string. VAL is the inverse of the STR$ function; it returns the number represented by the characters in a string argument. This num- ber may be integer, single precision, or double precision, depend- ing on the range of values and the rules used for typing all constants. VAL terminates its evaluation on the first character that has no meaning in a numeric value. If the string is nonnumeric or null, VAL returns a zero.

Ex amples PRINT VAL("1 00 DOLLARS") prints 100. PRINT VAL("1234E5") prints 123400000.

Sample Programs 10 READ NAME$, CITY$, STATE$, ZIP$ 20 IF VALCZIP$) < 90000 OR VAL(ZIP$) > 96699 THEN PRINT NAME$ TABC25) "OUT OF STATE" 30 IF VAL(ZIP$) > 90801 AND VAL

334 Chapter 10 I BASIC Keywords

VARPTR Function

VARPTR (variable) VARPTR ([#]buffer)

Returns the offset into BASIC’s data segment of a variable or a disk buffer. Variable is a numeric or string variable. Buffer is the number assigned to the file when you opened it. The number sign is optional. It is provided for compatibility with other BASICs. VARPTR can help you locate a value in memory. When used with Variable, it returns the address of the first byte of data identified with variable. See the section “How Variables are Stored” in Chapter 11 for the format. If the variable you specify has not been assigned a value, an “Il- legal function call” occurs. When used with sequential access files, VARPTR returns the starting address of the disk buffer. When used with direct access files, VARPTR returns the address of the FIELD buffer. If you specify a buffer that was not allocated when loading BASIC, a “Bad file number” error occurs. (See Chapter 2 for in- formation on how to load BASIC.) The offset returned is an integer in the range -32768 to 32767. It is always an offset into BASIC’s data segment, regardless of whether you have executed a DEF SEG to change the segment. VARPTR is used primarily to pass a value to an subroutine via USR. Since VARPTR returns an offset that indicates where the value of a variable is stored, you can pass this address to an assembly-language subroutine as the ar- gument of USR. The subroutine can then extract the contents of the variable with the help of the address that you have supplied to it. If VARPTR returns a negative address, add it to 65536 to obtain the actual address.

335 Chapter 10 I BASIC Keywords

VARPTR$ Function

VARPTR$(uaria ble)

Returns a character form of the memory address of the variable. VARPTR$ is primarily used with PLAY and DRAW in programs that are later executed. Variable is a numeric or string variable. VARPTR$ returns a 3-byte string:

byte 0 = type byte 1 = low byte of address byte 2 = high byte of address Type is 2 for integer variables, 3 for string variables, 4 for single precision variables, and 8 for double precision variables. Note: Because array and string addresses and file data blocks change whenever you assign a new vari- able, do not store the contents of VARPTR$ into a variable.

Example 10 PLCIY "X" +VARPTR$

336 ChuDter 10 I BASIC Keywords

VIE WIGraphics Statement

Creates a viewport that redefines the screen parameters. This defined area, a window, becomes the only place you can draw graphic displays. (XI,yI) specifies the upper-left coordinates for the rectangular viewport. (~232)specifies the lower-right coordinates for the rectangular viewport. All coordinates must be within the limitations of the screen. Color lets you fill in the specified viewport with the specified color. See Chapter 8, “Displaying Color and Graphics,” for infor- mation on color. Border is an integer in the range 0 to 15. See Chapter 8, “Dis- playing Color and Graphics,” for information on the 16 color set used for borders. SCREEN specifies that all coordinates used in drawing are ab- solute to Point 0,0 on the screen. If you omit SCREEN, all coor- dinates specified are relative to the viewport coordinates. If you omit all options, BASIC sets the viewport to define the en- tire screen. Examples VIEW (10,10)-(100,1 00) sets up a viewport with the upper-left corner at 10,10 and the lower-right corner at 100,100. Since SCREEN is omitted, all subsequent coordinates are relative to the viewport. For example, PSET (5,5),3actually sets point 15,15. VIEW SCREEN <20,25)-<100,150) sets up a viewport. Because SCREEN is specified, all subse- quent coordinates are absolute. For example, PSET (5,5),3 does not appear because it is outside the viewport. PSET (30,30),3 is within the viewport.

337 Chapter 10 I BASIC Keywords

Notes:

0 BASIC ignores any points that are outside the viewport's limits.

0 RUN, SCREEN, and WINDOW statements, without parame- ters, define the entire screen as the viewport. CLS clears only the active viewport. Sample Program 10 SCREEN 1 20 VIEW (1 0,10)-(200,100),2 30 PSET (100,50) 40 DRFlW "L40 E20 F20" Line 20 sets the viewport. Line 30 sets the starting point for the DRAW statement in Line 40.

~ 338 ChuDter 10 I BASIC Keywords

VIEW PRINT Statement

VIEW PRINT top line TO bottom line

Creates a text viewport that redefines the text screen parame- ters. All statements and functions that normally function within the text viewport now function in the new text screen parame- ters. Cursor movement and scrolling are also limited to the text viewport. Top line specifies the first line of the text viewport. It may be in in the range 1 to 24, but must be less than bottom line. If you omit top line, BASIC assumes Line 1 as the beginning of the text viewport. Bottom line specifies the last line of the text viewport. It may be in the range 1 to 24, but must be greater than top line. If you omit bottom line, BASIC assumes Line 24 as the end of the text viewport. If you omit all parameters, VIEW PRINT defines the entire screen as the text viewport. Example VIEW PRINT 1 TO 15 BASIC defines the first 15 lines of the video as the text viewport. All cursor movements, scrolling, and text screen functions and statements are limited to these boundaries.

339 Chapter 10 I BASIC Keywords

WAIT Statement

WAIT port, numberl [,number21

Suspends program execution until a machine input port develops a specified bit pattern. (A port is an inputloutput location.) Number1 and Number2 are integers in the range 0 to 255. BASIC reads the data at the specified port and XORs it with number2, if given. If you omit number2, BASIC XORs the data with zero. BASIC then ANDs the result with numberl. If the re- sult is zero, BASIC starts again with reading the data at the port again. If the result is nonzero, BASIC continues with the next statement. It is possible to enter an infinite loop with the WAIT statement. In this case, you must restart the machine manually. To avoid this, WAIT must have the specified value at port number during some point in program execution.

Example 100 WAIT 32,2

340 Chapter 10 I BASIC Ke.ywords

WHILE ...WEND Statement

WHILE expression WEND

Executes a series of statements in a loop as long as a given con- dition is true. Expression is any numeric or string expression, usually making logical or relational comparisons. If expression is true, BASIC executes the statements after the WHILE statement until it encounters a WEND statement. Then BASIC returns to the WHILE statement and checks expression. If it is still true, BASIC repeats the process. If it is not true, exe- cution resumes with the statement following the WEND statement. You may nest WHILE/WEND loops to any level. Each WEND matches the most recent WHILE. An unmatched WHILE state- ment causes a “WHILE without WEND” error, and an un- matched WEND causes a “WEND without WHILE” error.

Sample Program 90 “BUBBLE SORT ARRAY A$ 100 FLIPS=l “FORCE ONE PASS THRU LOOP 110 WHILE FLIPS 115 FLIPS=0 120 FOR I=l TO J-1 130 IF A$(I)>A$(I+l)THEN SWAP A$

341 ChaDter 10 I BASIC Kevwords

WIDTH Statement

WIDTH [LPRINT] size WIDTH buffer, size WIDTH device, size

Sets the line width in number of characters for the display, line printer, or communication channel. Size may be an integer in the range 0 to 255 that specifies the number of characters in a line. For the screen, size may be only 20, 40, or 80. Buffer is an integer in the range 0 to 15 and specifies the buffer used in the OPEN statment. When you specify buffer, BASIC changes the width immediately. This lets you change the width when the file is open. To return to the previous width, execute another WIDTH statement,. Device is a valid device enclosed in quotation marks that speci- fies on which device you want to set the width. See Chapter 1 for valid device names. When you specify device, BASIC stores the new width and does not change the current width of the device. When a subsequent OPEN statement opens that device, BASIC uses the new width while the file is open. After you close the file, the device returns to the previous width. When you set the width for the line printer, BASIC sends a car- riage return after every size character. For example: 10 WIDTH LPRINT 100 20 LPRINT "This line is 100 character5 long. See what happen5 when you print a 5tring longer than width . " Line 10 sets the printer width to 100 characters. After printing 100 characters, BASIC issues a carriage return. The carriage re- turn causes the printer to print the remaining characters on the next line.

342 Chapter 10 I BASIC Keywords

When you set the width for the communications channel, BASIC sends a carriage return after every size character up to and in- cluding 254. A width of 255, however, is interpreted as “infinite” width and disables line wrapping. The default for communica- tions channels is 255. To set WIDTH at the screen, you may omit the LPRINT option in the first form of the syntax, like this: WIDTH 40 or you may use the third form of the syntax and specify the device: WIDTH “SCRN:”, 40 You may only use the WIDTH statement to select a width of 80 if you are using the VM-2 Monochrome Monitor or CM-2 Color Monitor. If you are using the VM-2 Monochrome Monitor or the CM-2 Color Monitor, you should note the following: If you change the screen width, BASIC clears the screen and sets the background to black and the foreground to white. Changing the screen width does not affect the color enabling/ disabling value (burst value). If the current video memory (allocated through a CLEAR statement) is not enough to accommodate the new screen mode, BASIC issues an “illegal function call” error.

0 The table below shows the actual effect of WIDTH statements on the various modes. Given a particular mode and width, the table shows the new screen mode that results. Width 20 40 80 0 8 1 8 2 4s +o 3 8E 4 b 5 u 5 6

~ 343 Chawter 10 I BASIC Kevwords

If you attempt to select a size outside the range 0 to 255, an "il- legal function call" error results. Examples WIDTH LPRINT 132 WIDTH "LPTI :'I, 132 Both these statements change the printer width to 132. The sec- ond statement does not change the printer width until LPT1: is specified as the device in an OPEN statement. 10 WIDTH LPRINT 80

100 OPEN "LPT1 :I' FOR OUTPUT AS #1 150 PRINT #1 1000 WIDTH #I, 40 Line 10 changes the width of the printer to 80 characters. Line 150 prints the records as 80 characters each. After BASIC exe- cutes Line 1000, Line 150 prints the records as 40 characters each.

344 Chapter 10 I BASIC Ke.ywords

WINDOW Statement

Lets you change the physical coordinates of the screen (or cur- rent viewport) by defining “world coordinates.” World coordinates can be any single-precision floating point numbers, including numbers outside the physical range of the screen as defined by the VIEW statement. Note: The viewport is set to the entire screen by de- fault. For more information on viewports, see the VIEW command. (x1,yl)specifies the world coordinates for the upper-left corner of the screen. x is the horizontal coordinate, and y is the vertical coordinate. (~2~2)specifies the world coordinates for the lower-left corner of the display. x is the horizontal coordinate, and y is the vertical coordinate. The SCREEN option tells BASIC to set the coordinates like the screen display where the lesser y-coordinate is in the upper-left corner of the screen. If you omit screen, BASIC inverts the y-coordinates to show a true Cartesian coordinate system. That is, the lesser y-coordinate is in the lower-left corner of the screen. WINDOW lets you plot points outside the normal screen coordi- nate limits by setting new world coordinates to the screen. WIN- DOW transforms the new world coordinates onto the screen, usually altering the aspect ratio. Note: CIRCLE, GET, and PUT do not use world coordinates. You can easily plot graphs by specifying coordinates that are di- rectly proportional to the limits of the graph. For example, to plot the increase of sales from 1984 to 1987 with sales averaging 100,000 to 300,000, you can use the following command: WINDOW <1984,100000)-<1987,300000)

345 ChaBter 10 I BASIC Kevwords

The coordinates can be pictured for commands that use world coordinates:

If you give the command: WINDOW SCREEN (1984,100000)-(1987,300000) the coordinates can be pictured as follows for commands that use world coordinates:

Note: RUN, SCREEN and WINDOW statements, without parameters, define the entire screen as the window.

346 Chapter 10 I BASIC Ke.ywords

WRITE Statement

WRITE data[,data,...I

Writes data to the screen. Data can be any string or numeric expression or variables. If you omit data, BASIC outputs a blank line. The only difference between WRITE and PRINT is that WRITE prints commas between the data items and prints quotation marks around strings.

347 Chapter 10 I BASIC Keywords

WRITE# Statement

WRITE#buffer, data[,data,...I

Writes data to a sequential access disk file. Buffer is the number assigned to the file when you opened it. Data may be numeric or string expressions. If you specify more than one data item, separate the items with commas. WRITE# inserts commas between the data items it writes to disk. It delimits strings with quotation marks. Therefore, it is not necessary to put explicit delimiters between the data. WRITE# inserts a carriage return after writing the last data item to disk.

Example A$="": B$="NEWS" WRITE#I , A$ ,E$ writes the following image to disk: "MICROCOMPUTER" ,"NEWS"

348

Chapter 11 TECHNICAL INFORMATION

This chapter provides various information of a technical nature. If you are just beginning to use BASIC, you may want to skip this chapter until later.

Interfacing with Assembly-Language Subroutines This section is for users who call subroutines written in other languages from their BASIC programs. BASIC provides for inter- facing with subroutines through the USR function and through the CALL and the CALLS statements. You can load your assembly language subroutine into BASIC’s work area or into another segment of memory. We will show you both methods.

Memory Allocation Outside BASIC’s Work Area When you load BASIC, the DS (data segment) register is set to the address of BASIC’s work area. To access an area of memory outside this work area, execute a DEF SEG statement to specify the address of the segment of memory you are accessing. If you don’t execute a DEF SEG statement, your CALL, CALLS, or USR statements transfer control to an area within BASIC’s work area. After returning from the subroutine, execute another DEF SEG statement to restore the DS register to its original value. See DEF SEG in Chapter 10 for more information.

Memory Allocation Inside BASIC’s Work Area To set aside memory space for an assembly language subroutine within BASIC’s work area, use the IM: switch when you load BASIC. See Chapter 2 for a review of the start-up procedure.

351 Chapter 11 I Technical Information

The /M: switch sets the highest memory address that BASIC can use. The value that you specify with the /M: switch tells BASIC that it can use all memory up to that offset. Load your subrou- tine at that offset. Using the iM: switch prevents BASIC from de- stroying your subroutine. For example, BASIC /M:&HF000 sets the highest memory location that BASIC can use at hexade- cimal address EFFF. This reserves the highest 4K bytes of memory for your subroutine. You can load your subroutine at hexadecimal address &HF000 like this: BLOAD "SUBA.ASM", gHF000

Stack Space If you need more stack space when you call an assembly lan- guage subroutine, you can save the BASIC stack and set up a new stack for the subroutine. You must restore the BASIC stack before returning from the subroutine. You save the stack, create a new stack, and restore the stack in your subroutine.

Loading the Subroutine into Memory You can use the operating system or the POKE statement to load the subroutine into memory. You may assemble the routines with the Macro Assembler (available through your Radio Shack dealer) and link them with Linker. The Linker is part of the MS-DOS package. To load the program file, observe these guidelines:

0 Be sure that the subroutines do not contain any long references. Skip the first 512 bytes of the LINK output file and then read in the rest of the file.

352 Chapter 11 I Technical Information

Poking a Subroutine into Memory You can code short subroutines in machine language and use the POKE statement to put the code into memory. To do so, follow these steps: 1. Code the machine language instructions for your subroutine. 2. Put the assembly instruction code for each byte of the ma- chine language code into DATA statements, preceded by the &H symbols to denote that they are hexadecimal values. 3. Execute a loop that reads the DATA statements and POKES them into an area of memory. For example, the instruction code for the statement PUSH BP is 55. The DATA statement for that instruction is DATA &H55 After the loop is complete, the subroutine is in memory. Whether you are using the USR function or the CALL statement to call the subroutine, you must set the value of the subroutine entry point as the location specified in the first POKE statement.

CALL Statement When the CALL statement is executed, the following occurs: 1. For each parameter in the parameter list, the two-byte offset of the parameter’s location within the data segment (DS) is pushed onto the stack. If the parameter is a string variable, the offset points to the string descriptor. See the section “Ac- cessing String Parameters” in this appendix. 2. The BASIC return address code segment (CS) and offset (IP) are pushed onto the stack. 3. Control is transferred to the subroutine by an 8086 long call to the segment address given in the last DEF SEG state- ment and the offset given in uariabk.

353 Chapter 11 I Technical Information

When the CALL statement is executed, the operating system loads the CS (code segment) register with the value specified in the last DEF SEG statement. If you are CALLing a subroutine within BASIC’s work area, and no DEF SEG is required, the CS register is loaded with the address of BASIC’s work area. This address is shifted left 4 bits; in other words, which is the same as multiplying it by 16 decimal (10 hexadecimal). Then, the off- set of the subroutine is added to the segment address. Example 17100 + 0020 = 17120 17120 is the absolute address of the first instruction in the subroutine.

Technical Functions The called routine may destroy the previous contents of all regis- ters. If you want to save the contents of the registers, the first instructions in the subroutine must be a PUSH for each register, and the last instructions in the subroutine must be a POP to re- store the registers to their original value. You must execute a POP for every PUSH to maintain stack integrity. The subroutine may refer to the passed parameters as positive offsets to the Base Pointer (BPI. The CALLed routine must PUSH BP on the stack and then move the current stack pointer into BP. BP should be the first register you PUSH so that the parameters may be referenced as an offset to BP. The first 4 bytes of the stack contain the IP and CS register values that BASIC saves when the CALL is executed. To calculate the pa- rameters offset from the BP, use this equation: 2 * (total parameters - parameter position) + 6 = offset For example, the address of parameter 1 is at 10(BP), parameter 2 is at S(BP), and parameter 3 is at 6(BP).

354 Chapter 11 I Technical Information

Exiting the Subroutine The called routine must execute a RET number statement to ad- just the stack to the start of the calling sequence. The value of number is 2 times the number of parameters in the parameter list.

CALLS Statement The CALLS statement is the same as CALL except the argu- ments are passed as segmented addresses. CALLS should be used to access MS-FORTRAN routines. Because MS-FORTRAN routines need to know the segment value for each argument passed, the segment is pushed first, fol- lowed by the offset. CALLS pushes 4 bytes for each argument; therefore, the number in the RET statement (RETn) must be 4 times the number of arguments.

USR Function When the USR statement is executed, the operating system loads the CS (code segment) register with the value specified in the last DEF SEG statement. If you are accessing a subroutine within BASIC’s work area and no DEF SEG is required, the CS register is loaded with the address of BASIC’s work area. This address is shifted left 4 bits; which is the same as multiplying it by 16 decimal (10 hexadecimal). Then the offset of the subrou- tine is added to the segment address. Example

17100 + 0020 = 17120 This is the absolute address of the first instruction in the subroutine.

355 Chapter 11 I Technical Information

Technical Functions When the USR function call is made, register AL contains a value that specifies the type of argument that was given. The value in AL may be one of the following:

Value in AL Type of Argument 2 2-byte integer (two’s complement) 3 String 4 Single precision floating-point number 8 Double precision floating-point number

If the argument is a string, the DX register pair points to the “string descriptor.” See the section “Accessing String Variables” in this chapter. If the argument is a number, the BX register pair points to the Floating-point Accumulator (FAC) where the argument is stored: FAC is the exponent minus 128, and the binary point is to the left of the most significant bit of the mantissa. FAC-1 contains the highest 7 bits of mantissa with leading 1 suppressed (implied). Bit 7 is the sign of the number (0 =positive, 1= negative). If the argument is an integer: FAC-2 contains the upper 8 bits of the argument. FAC-3 contains the lower 8 bits of the argument.

If the argument is a single precision floating-point number: FAC-2 contains the middle 8 bits of mantissa. FAC-3 contains the lowest 8 bits of mantissa. If the argument is a double precision floating-point number: FAC-4 through FAC-7 contain 4 more bytes of mantissa (FAC-7 contains the lowest 8 bits).

Exiting the Subroutine The subroutine must execute a RET 7 statement to adjust the stack to the start of the calling sequence.

356 Chapter 11 I Technical Information

How Variables are Stored BASIC stores variables in its data segment as follows:

Byte Contents Description Byte 0 Type Identifies the type of vari- able stored at this location: 2 integer 3 string 4 single precision 8 double precision Bytes 1 and 2 Name The first 2 characters of the variable name. Byte 3 Integer Integer is the number of ad- 3 - 38 ditional characters in the variable name. Byte 4 + Name The remainder of the vari- integer stored able name is stored at bytes in Byte 3 4 + the integer stored in Byte 3. Byte 4 + length Data The contents of the variable are stored in the bytes im- mediately following the vari- able name. The data can be 2, 3, 4, or 8 bytes in length, depending on the type of data.

At least 3 bytes are required to store any variable name. A 1- or 2-character variable name occupies exactly 3 bytes. Bytes 1 and 2 for the first 2 characters and Byte 3 to contain a zero to indi- cate that there are no additional characters in the variable name. If the variable name only contains 1 or 2 characters, the data is stored beginning at Byte 4. As you can see, the location of the first actual byte of data depends on the length of the vari- able name. VARPTR returns the offset of the first actual byte of data, not the offset of the beginning of the storage area.

357 Chapter 11 1 Technical Information

Accessing String Variables If the parameter passed in a CALL statement is a string expres- sion, the parameters offset points to the string descriptor. If the argument passed in a USR function call is a string expression, the DX register points to the string descriptor. The string descriptor is a 3-byte area of memory that points to the text of the string. The string descriptor contains the following: Byte 0 contains the length of the string (0 to 255). Byte 1 contains the lower 8 bits of the string starting address in BASIC’s data segment. Byte 2 contains the upper 8 bits of the string starting address in BASIC’s data segment. The text of the string may be altered by the subroutine, but the length of the string must not be changed. BASIC cannot cor- rectly manipulate strings if their lengths are modified by exter- nal routines. Since the string descriptor points to an area of memory in your BASIC program, you must be careful not to alter or destroy your program. To avoid unpredictable results, add the concatenation symbol (+) to the string. This forces the string to be copied into string space, where the string may be modified without affecting the program. Example

20 A$ = “MONTHLY SALES REPORT” + “ ”

File Control Block A file control block is a storage area in BASIC’s data segment that contains information BASIC needs for all functions per- formed on that file. When you execute the VARPTR function and specify the buffer number, BASIC returns the address of the BASIC file control block for that file. Note that this is the BASIC file control block, not the DOS file control block. The address is specified as an offset into BASIC data segment. In this section we define the information in the file control block. Offsets are relative to the value returned by VARPTR. Length is in bytes.

358 Chapter 11 I Technical Information

OFFSET LENGTH DESCRIPTION 0 1 Mode The mode in which the file was opened: 1 - Input Only 2 - Output Only 4 - Random I/O 16 - Append Only 32 - Internal use 64 - Future use 128 - Internal use 1 38 FCB Disk File Control Block. Refer to DOS User's Guide for contents. 39 2 CURLOC Number of sectors read or written for sequential ac- cess. For random access, it contains the last record number + 1 read or written. 41 1 ORNOFS Number of bytes in sector when read or written. 42 1 NMLOFS Number of bytes left in In- put buffer. 43 3 *** Reserved for future expansion. 46 1 DEVICE Device number: 0-9 - Disks A: thru J: 255 - KYBD: 254 - SCRN: 253 - LPT1: 251 - COM1: 250 - COM2: 249 - LF'T2: (not available) 248 - LF'T3: (not available) 47 1 WIDTH Device width. 48 1 POS Position in buffer for PRINT#.

359 Chapter 11 I Technical Information

OFFSET LENGTH DESCRIPTION 49 1 FLAGS Internal use during LOAD/ SAVE; not used for data files. 50 1 OUTPOS Output position used during tab expansion. 51 128 BUFFER Physical data buffer. Used to transfer data between DOS and BASIC. Use this offset to examine data in Sequential I/O mode. 179 2 VRECL Variable length record size. Default is 128. Set by length option in OPEN statement. 181 2 PHYREC Current physical record number. 183 2 LOGREC Current logical record number. 185 1 *** Future use. 186 2 OUTPOS Disk files only. Output posi- tion for PRINT#, INPUT#, and WRITE#. 188 FIELD Actual FIELD data buffer. Size is determined by /S: switch. VRECL bytes are transferred between BUFFER and FIELD on I/O operations. Use this offset to examine File data in Ran- dom I/O mode.

360 Chapter 11 I Technical Information

User Installed Devices When writing device drives to use with BASIC, note the follow- ing rules:

0 BASIC sends only a carriage return as an end of line. If the device requires a line feed also, you must provide for this in your driver. BASIC must read and write control information to the device. Reading and writing Device Control data is handled by the BASIC IOCTL statement and the IOCTL$ function.

0 Your driver must provide the following control functions: The driver must set a maximum line width as requested by the OPEN statement. The driver must return the current maximum line width when BASIC asks for it. Input Devices must return an “end-of-file’’ condition to BASIC if you want to be able to close sequential input files open to the device driver. This is used by the EOF statement. Input Devices should return a “.Z [CTRL][q if BASIC attempts to read past the end of the device input stream. BASIC uses this to give an “Input past end” error. For more information on device drives, see the Programmer’s Reference Manual for your computer. It is available at your Radio Shack Computer Store.

Information for Creating Child Processes When writing programs for use as child processes from BASIC, please note the following rules and information: Child processes that use the screen device might modify the screen mode parameters. If necessary, restore these parame- ters from BIOS.

0 Save and restore interrupt vectors the child process uses. BASIC places many hardware devices in specific states. These devices include an Interrupt Controller, Counter Tim- ers, DMA Controller, I/O Latch, and Uarts.

361 Chapter 11 I Technical Information

Be careful when altering any files opened by the BASIC par- ent program. The BASIC parent program should close all files before executing SHELL and then reopen them upon return.

0 When the SHELL command executes, BASIC tries to free any memory not being used. However, BASIC does not free memory preserved with the /M switch. This may cause an “Out of memory” error. To avoid this, load your machine language routines before en- tering BASIC. Use Interrupt 27 to let the routines to exit MS-DOS but still remain in memory. For more information, see the Programmer’s Reference man- ual for your computer. It is available through your Radio Shack Computer Center.

0 Never use Interrupt 27 on a child process. If you attempt to terminate a child process but have it remain in memory, BASIC may not have enough room to expand its workspace to its original size. If the workspace cannot be restored, BASIC closes all files, prints the error message “SHELL can’t con- tinue,” and exits to MS-DOS. You cannot run BASIC as a child process to itself.

362

Chapter 12 BASIC ERROR CODES AND MESSAGES

Number Message

1 NEXT without FOR BASIC executed a NEXT statement without previ- ously executing a FOR statement, or a variable in a NEXT statement does not correspond to a previ- ously executed FOR statement. 2 Syntax error BASIC encountered a line that contains an incor- rect sequence of characters (such as unmatched pa- rentheses, misspelled statement, incorrect punctuation, etc.). BASIC automatically enters the edit mode at the line that caused the error. 3 RETURN without GOSUB BASIC executed a RETURN statement without pre- viously executing a GOSUB statement. 4 Out of DATA When executing a READ statement, BASIC could not find any DATA statements or unread data items. 5 Illegal function call A parameter that is out of range was passed to a math or string function. This error may also occur as the result of: negative array subscript or an unreasonably large array subscript. negative or zero argument with LOG.

0 negative argument to SQR.

0 negative mantissa with a noninteger exponent.

0 invalid exponential number

365 Chavter 12 I Error Messages

Number Message

0 a call to a USR function without a starting ad- dress set by DEF USR.

0 improper argument to MID$, LEFT$, RIGHT$, PEEK, POKE, TAB, SPC, STRING$, SPACE$, INSTR, or LEFT$, RIGHT$, PEEK, POKE, TAB, SPC, STRING$, SPACE$, INSTR, or ON ...GOTO.

0 negative record number used with GET or PUT. 6 Overflow The result of a calculation was too large to be rep- resented in BASIC numeric format. If underflow oc- curs, the result is zero, and execution continues without an error. 7 Out of memory A program is too large, has too many FOR loops or GOSUBs, has too many variables, or has expres- sions that are too complicated. 8 Undefined line number A nonexistent line was referenced in a GOTO, GO- SUB, IF... THEN ...ELSE, or DELETE statement. 9 Subscript out of range An array element is referenced with a subscript outside the dimensions of the array or with the wrong number of subscripts. 10 Redimensioned Array/Duplicate Definition BASIC encountered 2 DIM statements for the same array, or a DIM statement after the default dimen- sion of 10 had already been established for that array.

366 Chapter 12 I Error Messages

Number Mess age 11 Division by zero An expression includes division by zero, or the oper- ation of involution results in zero being raised to a negative power. BASIC supplies machine infinity with the sign of the numerator as the result of the division, or it supplies positive machine infinity as the result of the involution. Execution then continues. 12 Illegal direct A statement that is illegal as a command was en- tered at BASIC’s prompt. 13 Type mismatch A string variable name was assigned a numeric value or vice versa. A string function was given a numeric argument or vice versa. 14 Out of string space The amount of memory used by string variables ex- ceeded the amount of free memory. 15 String too long An attempt was made to create a string more than 255 characters. 16 String formula too complex A string expression is too long or too complex. The expression should be broken into smaller expressions. 17 Can’t continue An attempt was made to continue a program that: halted because of an error.

0 was modified during a break in execution.

0 does not exist.

367 Chapter 12 I Error Messages

Number Message 18 Undefined user function. A USR function was called before providing a func- tion definition (DEF USR statement). 19 No RESUME BASIC executed an error-handling routine that did- not have a RESUME statement. 20 RESUME without error BASIC executed a RESUME statement when no er- ror had occurred. 21 Unprintable error An error message is not available for the error that occurred. 22 Missing operand BASIC encountered an expression that contained an operator but no operand. 23 Line buffer overflow The line being input is too long. 24 Device Timeout BASIC did not receive information from an 110 de- vice within a predetermined amount of time. 25 Device Fault An incorrect device designation has been entered. 26 FOR without NEXT BASIC executed a FOR statement that did not have a matching NEXT. 27 Out of Paper BASIC received an out of paper status from the printer.

368 Chapter 12 I Error Messages

Number Message 29 WHILE without WEND BASIC encountered a WHILE statement that did not have a matching WEND. 30 WEND without WHILE BASIC executed a WEND statement before execut- ing a WHILE statement.

369 Chapter 12 I Error Messages

Disk Errors Number Message 50 FIELD overflow A FIELD statement is allocating more bytes than the specified record length of the direct access file. 51 Internal error An internal malfunction has occurred in BASIC. Report to Radio Shack the conditions under which the message appeared. 52 Bad file number BASIC encountered a reference to a buffer number that is not open or is out of the range of the number of files specified when BASIC was loaded. 53 File not found A LOAD, KILL, or OPEN statement references a file that does not exist on the current disk. 54 Bad file mode An attempt was made to use PUT, GET, or LOF with a sequential file, to LOAD a direct file, or to execute an OPEN statement with a file mode other than I, 0, R, E or D. 55 File already open BASIC encountered an OPEN statement for sequen- tial output, or a KILL statement, for a file that is already open. 57 Device I/O Error An Input/Output error occurred. This is a fatal er- ror; the operating system cannot recover it. 58 File already exists The filename specified in a NAME statement is identical to a filespec already in use on the disk.

370 Chapter 12 I Error Messages

~~

Number Message 61 Disk full All disk storage space is in use. 62 Input past end BASIC executed an INPUT statement after all the data in the file had been read, or BASIC executed an INPUT statement to a null (empty) file. To avoid this error, use the EOF function to detect the end- of-file. 63 Bad record number In a GET or PUT statement. the record number is either greater than the max mum allowed (16,777,215) or equal to zero. 64 Bad file name An illegal pathname was used with a LOAD, SAVE, KILL, or OPEN statement (for example, a filename with too many characters). 66 Direct statement in file Information in a non-ASCII format was encountered while LOADing an ASCII-format file. The LOAD is terminated. 67 Too many files The diskette already contains the maximum num- ber of files allowed. This usually occurs on SAVE or OPEN. An attempt was made to create a new file (using SAVE or OPEN) when all directory entries are full. 68 Device Unavailable An attempt was made to open a file to a non- existent device. It may be that hardware does not exist to support the device, such as LPT2: or LPT3:, or that the device is disabled. This occurs if an OPEN “COM1: ... statement is executed but the user disabled RS232 support via the /C:0 switch direc- tive on the command line.

371 Chapter 12 I Error Messages

Number Message

69 Communication buffer overflow Not enough space has been reserved for the commu- nications buffer. 70 Disk write protected Occurs when an attempt is made to write to a diskette that is write-protected. Use an ON ERROR GOTO statement to detect this situation and re- quest user action. 71 Disk not Ready Occurs when the diskette drive door is open or a diskette is not in the drive. Use an ON ERROR GOTO statement to recover. 72 Disk media error Occurs when the FDC controller detects a hardware or media fault. This usually indicates harmed me- dia. Copy any existing files to a new diskette and re-format the damaged diskette. FORMAT flags any bad tracks and records them in a special file. The remainder of the diskette is then usable. 73 Advanced Feature 74 Rename across disks An attempt was made to rename a file with a new drive designation. BASIC does not allow this. 75 PatWFile Access Error During an OPEN, MKDIR, CHDIR, or RMDIR op- eration, MS-DOS was unable to make a correct Path-to-Filename connection. 76 Path not found The OPEN, MKDIR, CHDIR, or RMDIR statement references a path that does not exist. 77 Deadlock

372

Appendix A BASIC Reserved Words and Derived Functions

Reserved BASIC Words ABS DELETE IOCTL OR SOUND AND DIM IOCTL$ OUT SPACE$ ASC DRAW KEY PAINT SPC ( ATN EDIT KEY$ PALETTE SQR AUTO ELSE KILL PALETTE USING STEP BEEP END LEFT$ PCOPY STICK BLOAD ENVIRON LEN PEEK STOP BSAVE ENVIRON$ LET PEN STR$ CALL EOF LINE PLAY STRIG CDBL EQV LIST PMAP STRING$ CHAIN ERASE LLIST POINT SWAP CHDIR ERDEV LOAD POKE SYSTEM CHR$ ERDEV$ LOC POS TAB( CINT ERL LOCATE PRESET TAN CIRCLE ERR LOF PRINT TERM CLEAR ERROR LOG PRINT# THEN CLOSE EXP LPOS PSET TIME$ CLS FIELD LPRINT PUT TIMER COLOR FILES LSET RANDOMIZE TO COM FIX MERGE READ TROFF COMMON FN MID$ REM TRON CONT FOR MKDIR RENUM USING cos FRE MKD$ RESET USR CSRLIN GET MKI$ RESTORE VAL CSNG GOSUB MKS$ RESUME VARPTR CVD GOT0 MOD RETURN VARPTR$ CVI HEX$ MOTOR RIGHT$ VIEW cvs IF NAME RMDIR WAIT DATA IMP NEW RND WEND DATE$ INKEY$ NEXT RSET WHILE DEF INP NOISE RUN WIDTH DEFDBL INPUT NOT SAVE WINDOW DEFINT INPUT# OCT$ SBN WRITE DEFSNG INPUT$ OFF SCREEN WRITE# DEFSTR INSTR ON SGN XOR DEFFN INT OPEN SHELL DEF USR INTER$ OPTION SIN

375 Appendix A

~

Derived BASIC Functions Functions which are not intrinsic to BASIC may be calculated as follows: Function BASIC Equivalent

SECANT SEC(X)= 1/COS(X) COSECANT CSC(X) = l/SIN(X) CONTANGENT COT(X)= l/TAN(X) INVERSE SINE ARCSIN(X) = ATN(X/ SQR( - X*X + 1)) INVERSE COSINE ARCCOS(X) = - ATN(X/ SQR( - X*X + 1))+ 1.5708 INVERSE SECANT ARCSEC(X)= ATN(X/ SQR(X*X - 1))+ (SGN(X)- 1) *1.5708 INVERSE ARCCSC(X)= ATN(X/SQR(X*X - 1)) COSECANT + (SGN(X)- 1)*1.5708 INVERSE COTANGENT ARCCOT(X) = ATN(X) + 1.5708 HYPERBOLIC SINE SINH(X) = (EXP(X)- EXP( - X))/2 HYPERBOLIC COSINE COSH(X)= (EXP(X)+ EXP( - X))/2 HYPERBOLIC TANH(X) = (EXP(X)- EXP( - XI)/ TANGENT (EXP(X)+ EXP( - X)) HYPERBOLIC SECANT SECH(X)= 2/(EXP(X)+ EXP( - XI) HYPERBOLIC COSECANT CSCH(X) = SI(EXP(X1- EXP( - XI) HYPERBOLIC COTH(X)= (EXP(X)+ (EXP( - X))/ COTANGENT (EXP(X)- EXP( - X)) INVERSE HYPERBOLIC ARCSINH(X1= LOG(X SINE + SQR(X*X + 1)) INVERSE HYPERBOLIC ARCCOSH(X) = LOG(X COSINE + SQR(X*X - 1)) INVERSE HYPERBOLIC ARCTANH(X) = LOG((l+XI/( 1- X))/ TANGENT 2

376 Appendix A

Function BASIC Equivalent INVERSE HYPERBOLIC ARCSECH(X) = LOG((SQR SECANT ( - x*x+ 1) + 1)/X) INVERSE HYPERBOLIC ARCCSCH(X) = LOG((SGN(X)* COSECANT SQR(X*X + 1)+ l)/X) INVERSE HYPERBOLIC COTANGENT ARCCOTH(X) =LOG((X + l)/(X - 1))/2

377

Appendix B KEYBOARD AND CHARACTER CODE CHARTS

Keyboard ASCIIiScan Codes The first table in this appendix lists the keys on the Tandy 1000 keyboard in scan code order, along with the ASCII codes they generate. For each key, the following entries are given: Scan Code - A value in the range 01H-5AH which uniquely identifies the physical key on the keyboard that is pressed. Keyboard Legend - The physical marking(s) on the key. If there is more than one marking, the upper one is listed first. ASCII Code - The ASCII codes associated with the key. The four modes are: Normal - The normal ASCII value (returned when only the indicated key is depressed). SHIFT - The shifted ASCII value (returned when SHIFT is also depressed). CTRL - The control ASCII value (returned when CTRL is also depressed.) ALT - The alternate ASCII value (returned when ALT is also depressed). Remarks - Any remarks or special functions. The following special symbols appear in the table: x Values preceded by an “x” are extended ASCII codes (codes preceded by an ASCII NUL, 00). - No ASCII code is generated.

* No ASCII code is generated, but the special function described in the Remarks column is performed.

379 Appendix B

The IALT] key provides a way to generate the ASCII codes of deci- mal numbers in the range 1 to 255. Hold down the [ALTI key while you type on the numeric keypad any decimal number in the range 1 to 255. When you release [, the ASCII code of the number typed is generated and displayed. Note: When the NUM LOCK light is off, the Normal and SHIFT columns for these keys should be reversed.

All numeric values in the table are expressed in hexadecimal.

QWERTY (USA) - Tandy 1000

ASCII Codes Scan Keyboard SHIFT CTRL Code Legend Normal ALT Remarks 01 ESC 1B 1B 1B x8B 02 1 ! 31 21 xEl x78 03 2 @ 32 40 x03 x79 04 3 # 33 23 xE3 x7A 05 4 $ 34 24 xE4 x7B 06 5 % 35 25 xE5 x7C 07 6 36 5E 1E x7D 08 7 &? 37 26 xE7 x7E 09 8 * 38 2A xE8 x7F 0A 9 ( 39 28 xE9 x80 OB 0 1 30 29 xE0 x81 0c - 2D 5F 1F x82 0D - + 3D 2B xF5 x83 BE BACK SPACE 08 08 7F x8C 0F TAB 09 x0F x8D x8E 10 Q 71 51 11 x10 11 W 77 57 17 xll 12 E 65 45 05 x12 13 R 72 52 12 x13 14 T 74 54 14 x14 15 Y 79 59 19 x15 16 U 75 55 15 x16 17 I 69 49 09 x17 18 0 6F 4F OF x18 19 P 70 50 10 x19 1A [ { 5B 7B 1B xEB 1B 1 I 5D 7D 1D xF0 1c ENTER OD OD OA x8F Main Keyboard 1D CTRL * * * * Control Mode 1E A 61 41 01 xlE 1F S 73 53 13 xlF 20 D 64 44 04 x20 21 F 66 46 06 x21 22 G 67 47 07 x22

380 Appendix B

ASCII Codes Scan Keyboard SHIFT CTRL Code Legend Normal ALT Remarks

23 H 68 48 08 x23 24 J 6A 4A OA x24 25 K 6B 4B OB x25 26 L 6C 4c 0c x26 27 3B 3A xF6 xF8 28 27 22 xF7 xF1 29 UP ARROW x48 x85 x90 x91 2A SHIFT * * * * Left SHIFT 2B LEFT ARROW x4B X87 x73 x92 2c Z 7A 5A 1A x2c 2D X 78 58 18 x2D 2E C 63 43 03 x2E 2F V 76 56 16 x2F 30 B 62 42 02 x30 31 N 6E 4E OE x3 1 32 M 6D 4D OD x32 33 < 2c 3c xF9 x89 34 > 2E 3E xFA x8A 35 I ? 2F 3F xFB xF2 36 SHIFT * * * * Right SHIFT 37 PRINT 10 * x72 x46 SCR Print Toggle 38 ALT * * * * Alternate Mode 39 space bar 20 20 20 20 3A CAPS * * * * Caps lock 3B F1 x3B x54 x5E x68 3c F2 x3c x55 x5F x69 3D F3 x3D x56 x60 x6A 3E F4 x3E x57 x6 1 x6B 3F F5 x3F x58 x62 x6C 40 F6 x40 x59 x63 x6D 41 F7 x4 1 x5A x64 x6E 42 F8 x42 x5B x65 x6F 43 F9 x43 x5c x66 x70 44 F1O x44 x5D x67 x7 1 45 NUM LOCK * * * * number lock 46 HOLD * * * * Freeze display 47 7 \ 37 5c x93 * 48 8 38 7E x94 * 49 9 PG UP 39 x49 x84 * 4A DOWN ARROW x50 x86 x96 x97 4B 4 I 34 7C x95 * 4c 5 35 xF3 xFC * 4D 6 36 xF4 xFD * 4E RIGHT ARROW x4D X88 x74 xEA 4F 1 END 31 x4F x75 * 50 2 32 60 x9A * 51 3 PG DN 33 x5 1 x76 * 52 0 30 x9B x9c * 53 DELETE 2D x53 x9D x9E

381 Appendix B

ASCII Codes Scan Keyboard SHIFT CTRL Code Leeend Normal ALT Remarks 54 BREAK xOO xOO * * CTRLBREAK is the control brk routine (INT 1BH). ALT BREAK is the scroll lock bit toggle. 55 + INSERT 2B x52 x9F xA0 56 . 2E xAl xA4 xA5 Numeric keypad 57 ENTER 0D OD 0A x8F Numeric keypad 58 HOME x47 x4A x77 xA6 59 F11 x98 xA2 xAC xB6 5A F12 x99 xA3 xAD xB7

382 Awwendix B

ASCII Character Codes The previous table listed the ASCII codes (in hexadecimal) gen- erated by each key. The following table lists the characters gen- erated by those ASCII codes. (Note: All ASCII codes in this table are expressed in decimal form.) You can display the characters listed by doing either of the following:

0 Using the BASIC statement PRINT CHR$(code), where code is the ASCII code.

0 Pressing and, without releasing it, typing the ASCII code on the numeric keypad. For Codes 0-31, the table also lists the standard interpretations. The interpretations are usually used for control functions or communications. Note: The BASIC program editor has its own special interpretation of some codes and may not display the character listed.

383 Appendix B

ASCII CHARACTER CODES

~ ~ ASCII Control code Character Character

000 (null) NUL 00 1 @ SOH 002 e STX 003 V ETX 004 + EOT 005 ENQ 006 ACK 007 (beep) BEL 008 13 0s 009 (tab) HT 010 (line feed) LF 01 1 (home) VT 01 2 (form feed) FF 013 (carriage return) CR 014 43 so 015 1J SI 01 6 b DLE 01 7 4 DC 1 018 t DC2 01 9 !! DC3 020 ll DC4 02 1 5 NAK

022 I SY N 023 1. ETB 024 t CAN 025 J EM 026 * SUB 027 t ESC 028 (cursor right) FS 029 (cursor left) GS 030 (cursor up) RS 03 1 (cursor down) us

384 Appendix B

ASCII CHARACTER CODES ASCII ASCII Code Character Code Character

032 (space) 068 D 033 ! 069 E 034 9, 070 F 035 # 071 G 036 $ 072 H 037 % 073 I 038 & 074 J 039 075 K 040 ( 076 L 041 1 077 M 042 078 N 043 + 079 0 044 080 P 045 - 08 1 Q 046 082 R 047 I 083 S 048 0 084 T 049 1 085 U 050 2 086 V 05 1 3 087 W 052 4 088 X 053 5 089 Y 054 6 090 Z 055 7 09 1 [ 056 8 092 \ 057 9 093 1 058 094 A 059 , 095 - 060 < 096 06 1 - 097 a 062 > 098 b 063 ? 099 C 064 @ 100 d 065 A 101 e 066 E? 102 f 067 C 103 9

385 Appendix B

ASCII CHARACTER CODES

ASCII ASCII Code Character Code Character

104 h 140 I 105 I 141 I 106 j 142 A 107 k 143 R 108 I 144 E 109 m 145 E 110 n 146 R

A 111 0 147 0 112 P 148 0 113 q 149 6 114 r 150 U 115 S 151 b 116 t 152 Y 117 U 153 0 118 v 154 U 119 W 155 a 120 X 156 E 121 Y 157 'f 122 z 158 Pt 123 { 159 I 124 I 160 a 125 1 161 I 126 - 162 6 127 0 163 -u 128 c 164 -n 129 ii 165 N 130 e,. 166 a 131 a 167 o_ 132 a 168 i 133 a 169 r 134 Q 170 1 135 F 171 '/2 136 6 172 '/4 137 e 173 I 138 e 174 (( )) 139 I 175

386 Appendix B

ASCII CHARACTER CODES

ASCII ASCII Code Character Code Character

176 3 21 2 177 2 213 178 i% 214 179 I 215 180 i 216 181 =I 21 7 182 il 218 183 n 219 184 220 J- 185 4 221 186 I1 222

187 =il 223

188 3 224 189 11 225 190 =I 226

191 7 227 192 L 228 193 I 229 194 T 230 195 1 23 1 196 - 232 197 + 233 198 t 234 199 It 235 200 e 236 201 ti= 237 202 JL 238 - 203 ir 239 204 1: 240 205 - 24 1 206 4; 242 207 I 243 208 Y 244 209 =F 245

210 7 246

21 1 L 247

387 Appendix B

ASCII CHARACTER CODES

ASCII ASCII Code Character Code Character

248 0 252 'I 249 0 253 2

250 0 254 w 251 If 255 (blank 'FF')

388 Appendix C VIDE 0 DISPLAY WORKSHEET

The following page contains a video display worksheet of your text screen’s coordinates. This map is provided to help you quickly position the cursor for screen prints. You’ll find it espe- cially useful for creating visually pleasing, easy-to-follow screen menus. See the CSRLIN and POS function for information on re- turning the current cursor position. See the LOCATE statement and the TAB function for information on positioning the cursor.

389 390 Appendix D EXTENDED CODES

For certain keys and key combinations, INKEY$ returns a 2- character code. The first character is a null character (ASCII Code 00). The second is usually the scan code of the key(s) pressed. The key(s) and associated ASCII codes (in decimal) are listed below.

Second Key(s) Second Key($ Character Pressed Character Pressed 15 64 16 65 17 66 18 67 19 68 20 71 21 72 22 73 23 75 24 77 25 79 30 81 31 82 32 83 33 84 34 85 35 86 36 87 37 88 38 89 44 90 45 91 46 92 47 93 48 94 49 95 50 96 59 97 60 98 61 99 62 100 63 101

391 Appendix D

Second Key(s) Second KeyW Character Pressed Character Pressed 102 122 103 123 104 124 105 125 106 126 107 127 108 128 109 129 110 130 111 131 112 132 113 152 115 153 116 162 117 163 118 172 119 173 120 182 121 183

392 INDEX

ABS Fn 92, 97 Absolute coordinates 82 Absolute value 97 Active page 80, 303 Addition 52 ALT key 38 AND 54 Animation 171, 282 Arctangent 99 Arguments 8 Arithmetic operators 51 Arrays 59-63, 117, 142, 152, 248 defining 63, 142 erasing 152 types 62 ASC Fn 92, 98 ASCII codes 98, 112, 302, 379-388 Aspect ratio 77, 78 Assembly-language subroutines 351-356 CALL 105 calling 105 DEFUSR 140 interfacing 351-353 loading 352 poking 353 USR 333 ATN Fn 92, 99 AUTO St 87, 100

Background colors 78, 79, 80 Backups 17-19 BASIC commands 33 concepts 43-56 derived function 376-377 device names 14 directory paths 12-13 disk files 11 editing 33-36 line numbers 43, 100 loading 19, 27

393 Index

BASIC (cont.) loading options 19-21 pathnames 12-13 program 43 redirection 21, 23-24 reserved words 375 sample session 27-29 special keys 36-38 statement 43 wildcards 13 work area 351-352 BEEP St 87, 101 BLOAD St 87, 102-103, 104 Boolean operators 54 Borders 80 Branching 172, 173, 175-176, 231 BSAVE St 87, 102-103, 104 Buffer 8, 159-160,215, 242, 298, 342-343 Buffer, communications 21, 208, 211, 244-247, 279, 281 Buffer, music 264 Buffer, printer 213

CALL St 87, 105, 353-355 Calling subroutines 105, 140 CALLS St 87, 106, 355 CDBL Fn 92, 107 Chaining 108, 126 CHAIN St 108, 126 CHOIR St 87, 111 Child processes 306-307,361-362 CHR$ Fn 92, 112 CINT Fn 92, 113 CIRCLE St 87, 114-116 CLOSE St 87, 119, 291 Clear 117-118, 120, 223 memory 117-118,223 screen 120 CLEAR St 87, 117-118 CLS St 87, 120 Color 78-79, 121-122, 123, 250, 253, 255, 303 COLOR/Graphics St 87, 121-122 Color sets 78-79

394 Index

COLOR/TextSt 87, 123 COM St 87, 124-125 COM/Trap St 87, 124-125 Commands 33 Comments 43, 288 COMMON St 87, 126 Communications 151, 169, 208, 211, 244-247, 281 Communications buffer 21, 208, 211, 281 Communications trapping 124-125, 226-227 Compressed files 300 Concatenation 52 Concepts 43-56 Constants 46-47 classifying 47-49 declaring 47-49 CONT St 87, 127, 316 Converting precision 49-50 107, 113, 129 Converting strings 317, 334 Coordinates 82 absolute 82 relative 82 physical 266, 267, 345-346 world 266, 267, 345-346 COS Fn 92, 128 Cosine 128 CSNG Fn 92, 129 CSRLIN Fn 92, 130 Current segment 138-139 Cursor 130, 209, 269 CVD Fn 92, 131 CVI Fn 92, 131 CVS Fn 92, 131

Data 44-46 constants 46-47 converting 49-50, 107, 113, 129, 221 double precision 45, 48,49, 107, 131, 221 hexadecimal 45, 174 integers 44, 113, 131, 163, 187, 221 manipulating 51 numeric 44-46 octal 46, 225 printing 214 single precision 45, 48, 49, 129, 221 strings 44, 49, 136, 185-186, 196, 197, 295

395 Index

DATA St 87, 132-133, 286-287, 292 Data files 21, 242-243, see also Disk files Date, retrieving 134-135 Date, setting 134 DATE$ Fn 92, 134-135 Debugging 127, 316, 332 DEFDBL St 87, 136 DEFFN St 87, 137 DEFINT St 87, 136 DEFSEG St 87, 138-139 DEFSNG St 87, 136 DEFSTR St 87, 136 DEFUSR St 87, 140 DELETE St 87, 141 Derived functions 376-377 Device errors 153, 154 Device names 14 Devices 14, 242-243, 342, 361 DIM St 63, 87, 142 Direct access 70-73, see also Disk files Directories 11, 111 changing 111 creating 220 displaying 161-162 removing 296 Directory path 12 Disk files buffer 8, 159-160, 215, 242, 298 CLOSE 119 closing 291 converting data 131 direct access 70-73 accessing 73-74, 168 closing 119 creating 71-73 EOF 150 FIELD 159-160 GET 168 locating records 207 LSET 215 MKD$ 221 MKI$ 221 MKS$221 OPEN 242-243

396 Index

Disk files (cont.) PUT 280 RSET 298 displaying 161-162 end of file 150 FIELD 159-160 file control block 358-360 length 210 LOAD 206 LOF 210 MERGE 216-217 OPEN 242-243 renaming 222 sequential access 67-70 closing 119 creating 68-69 end of file 150 EOF 150 INPUT# 181-182 IN PUT$ 183-184 LINE INPUT# 203 locating records 207 OPEN 242-243 PRINT# 276-278 PRINT# USING 276-278 updating 69-70 Diskcopy 18-19 Display page 80, 303 Division 52 integer 52 Double precision 45 CDBL 107 CVD 131 DEFDBL 136 MKD$ 221 DRAW St 87, 143-145 Draw point 279

EDIT St 88, 146 Editing 33-36, 146 END St 88, 147 End of file 150 ENVIRON St 88, 148 ENVIRON$ Fn 88, 149 Environment String Table 148, 149

397 Index

EOF Fn 92, 150-151 Equal sign 52 EQV 54 ERASE St 88, 152 ERDEV Fn 92, 153 ERDEV$ Fn 92, 154 ERL St 88, 155 ERR St 88, 156 ERROR St 88, 157 Error codes 365-373 Error messages 365-372 Errors 153-157, 365-372 device 153-154 ERDEV 153 ERDEV$154 ERL 155 ERR 156 ERROR 157 RESUME 293 simulate 157 trapping 156, 157, 228 EXP Fn 92, 158 Exponent, natural 158 Exponential numbers 48 Exponentiation 51 Expressions 51, 175 Extensions 12

FIELD St 88, 159-168 File control block 358-360 Filenames 12, 13 Files see Disk files FILES St 88, 161-162 FIX Fn 92, 163 Format 18-19 Formatting printing 214, 270-275 FOR/NEXT St 88, 164-166 FORTRAN routines 106 FRE Fn 92, 167 Function keys 190-193 assigning 190 displaying 191 trapping 192-193, 232-233 Functions 56, 92-94 Function, user 137

398 Index

GET/Communications St 88, 169 GET/Graphics St 88, 170-171 GET St 88, 131, 168 GOSUB St 88, 172, 294 GOTO St 88, 173 Graphics 77-82, 114-116, 143-145, 199-201, 250-252, 253-254, 255-256, 279, 282-284, 303-304, 337-338 Graphics modes 80-82 Greater Than sign 52 Greater Than/Equal To sign 53

HEX$ Fn 93, 174 Hexadecimal 7, 45, 174 Hierarchy of operators 55-56

IF/THEN/ELSE St 88, 175-176 Image file 102-103, 104 IMP 54 Inequality sign 52 INKEY$ Fn 93, 177 INP Fn 93, 178 INPUT St 88, 179-180 INPUT# St 88, 181-182 INPUT$ St 88, 183-184 Input communications 169 device 181-182 disk 168, 181-182, 183-184, 203 graphics 170-171 keyboard 177, 179-180, 183-184, 202 joysticks 315, 319-320 light pen 259 memory 258 music buffer 264 port 178, 340 Input, redirection 23-24 INSTR Fn 93, 185-186 INT Fn 93, 187 Integer division 52 Integers 44, 48, 49 ClNT 113 CVI 131 DEFDBL 136

399 Index

Integers (cont.) FIX 163 INT 187 MKI$ 221 IOCTL St 88, 188 IOCTL$ Fn 93, 189

Joystick 315, 318, 319-320 Trapping 238-239, 321-322

KEY St 88, 190-191, 194 Keyboard codes 379-388 Keyboard input 177, 179-180, 183-184, 202 Keys 36-39, 193 Keys, user-defined 193 KEY/Trap St 88, 192-193 Key trapping 192-193, 232-233 KILL St 88, 194

LCOPY 88, 195 LEFT$ Fn 93, 196 LEN Fn 93, 197 Less Than sign 52 Less Than/Equal To sign 53 LET St 88, 198 Light pen trapping 234, 260 LINE St 88, 199-201 LINE INPUT St 88, 202 LINE INPUT# St 88, 203 Line length 33 Line numbers 43 automatic 100 LIST St 89, 204 LLIST St 89, 205 LOAD St 28-29, 89, 206 Loading BASIC 19, 27 Basic options 19-21 MS-DOS 17 programs 28-29, 206 LOC Fn 93, 207-208 LOCATE St 89, 209 Locating cursor 130, 269 Locating record 207

400 Index

LOC/Communication Fn 93, 208 LOF Fn 93, 210-211 LOF/Communication Fn 93, 211 LOG Fn 93, 212 Logarithms 158, 212 Logical operators 54-55 LOOPS164-166 LPOS Fn 93, 213 LPRINT St 89, 214, 326 LPRINT USING St 89, 214, 326 LSET St 89, 215

Memory allocation 351-352 Memory image file 102-103, 104 Memory read 258 Memory size 20, 117-118, 138, 167 MERGE St 89, 216-217 MID$ Fn 93, 219 MID$ St 89, 218 MKD$ Fn 93, 221 MKDIR St 89, 220 MKI$ Fn 93, 221 MKS$ Fn 93, 221 MOD 52 Modulus arithmetic 52 MS-DOS 11, 306-307, 325 child processes 306 directory path 12-13 directory structure 11 loading 17 names 13 pathnames 12 root 11 SYSTEM 325 Multiplication 52 Music 261-265 buffer 264 PLAY 261-265 trapping 236-237, 265

NAME St 89, 222 Natural exponent 158 Natural logarithm 212 Negation 51

401 Index

Nested loops 165-166 NEW St 89, 223 NOISE St 89, 224 NOT 54 Notations 7 Numbers converting 49-50, 107, 113, 129, 221 double precision 45, 48, 49, 107, 131, 221 hexadecimal 45, 174 integers 44, 113, 131, 163, 187, 221 octal 46, 225 single precision 45, 48, 49, 129, 221 Numeric constants 46 Numeric data 44-46 Numeric variables 47

OCT$ Fn 93, 225 Octal 7, 46, 225 ON COM()GOSUB St 89, 124, 226-227 ON ERROR GOTO St 89, 228, 293 ON/GOSUB St 89, 229-230, 294 ON/GOTO St 89, 231 ON KEY()GOSUB St 89, 193, 232-233 ON PEN GOSUB St 89, 234-235, 260 ON PLAY()GOSUB St 89, 236-237, 265 ON STRIG()GOSUB St 89, 238-239, 318, 321-322 ON TIMER()GOSUB St 89, 240-241, 331 OPEN St 89, 242-243 0PEN"COM St 89, 244-247 Operators 51-56 arithmetic 51-52 hierarchy 55-56 logical 54-55 relational 52-54 string relational 53-54 OPTION BASE St 89, 248 OR 54 OUT St 89, 249 output communication 281 disk 276-278, 280, 348 display 204, 270-271, 272-275, 279, 326, 347 graphics 282-284 memory 268

402 Index

Output (cont.) music 261-263 port 249 printer 205, 214, 326 sound 101, 117, 224 Output redirection 23-24

Pages, video 79-80 PAINT St 90, 250-252 PALETTE St 90, 253-254 Palettes 78-79, 121 PALETTE USING St 90, 255-256 Parameters 8 Pathnames 12 PCOPY St 90, 257 PEEK Fn 94, 258, 268 PEN Fn 94, 259 PEN/Trap St 90, 234-235, 259, 260 Physical coordinates 266, 267, 345-346 PLAY Fn 94, 264 PLAY St 90, 261-263 PLAY/Trap St 90, 236-237, 265 PMAP Fn 94, 266 POINT Fn 94, 267 POKE St 90, 258, 268 Ports 178, 249, 340 POS Fn 94, 269 Position cursor 209 Precision conversion 49-50, 107, 113, 129 PRESET St 90, 279 PRINT St 90, 270-271, 326 PRINT# St 90, 276-278 PRINT# USING St 90, 276-278 Print buffer 213 Printer 205, 213, 214, 326, 342-344 Printing, formatted 214, 270-275 PRINT USING St 90, 272-275 Program elements 43 execution 299 line numbers 43, 289-290 lines 33, 289-290 listing 204, 205 loops 164-166,341

403 Index

Program merging 216-217 Program renumbering 289-290 Program termination 147, 316 PSET St 90, 279 PUT St 90, 280 PUT/Communication St 90, 281 PUT/Graphics St 90, 282-284

RANDOMIZE St 90, 285, 330 Random numbers 285, 297 READ St 90, 132-133, 286-287, 292 Records 67 Record size 21 Redirection 21, 23-24 Relational operators 52-54 with strings 53-54 Relative coordinates 82 REM St 90, 288 Remarks 43, 288 Removing directories 296 Removing files 195 Removing lines 141 Removing programs 223 Renaming files 222 RENUM St 90, 289-298 Reserved words 375 RESET St 90, 291 Resolution 77-78 RESTORE St 90, 292 RESUME St 90, 293 Retrieving date 134-135 Retrieving ti me 328-329 RETURN St 90, 294 RIGHT$ Fn 94, 295 RMDIR St 90, 296 RND Fn 94, 297 Root directory 11 RSET St 90, 298 RUN 29 RUN St 90, 299 Sample session 27-29 SAVE St 28, 91, 300-301 Saving programs 28, 300-301

404 Index

Scan codes 379-382 SCREEN Fn 94, 302 SCREEN St 91, 303-304 Screen, clear 120 Screen modes 80-82, 303-304 Search, strings 185-186 Segment address 138-139 Sequential access files 67-70 closing 119 creating 68-69 end of file 150 EOF 150 INPUT# 181-182 IN PUT$ 183-184 LINE INPUT# 203 locating records 207 OPEN 242-243 PRINT# 276-278 PRINT# USING 276-278 Updating 69-70 Setting date 134 Setting time 328 SGN Fn 94, 305 SHELL St 91, 306-307 SIN Fn 94, 308 Sine 308 Single precision 45, 48, 49 CSNG 129 CVS 131 DEFSNG 136 MKS$ 221 SOUND St 91, 101, 117, 224, 264, 309-311 SPACE$ Fn 94, 312 SPC Fn 94, 313 Speakers 101, 224, 309-311 Special keys 36-38 SQR Fn 94, 314 Square root 314 Stack space 117 Statements 43, 87-91 STICK Fn 94, 315 STOP St 91, 127, 316 STR$ Fn 94, 317, 334

405 Index

STRIG Fn 94, 319-320 STRIG St 91, 119, 318 STRIG/TrapSt 91, 117, 238-239, 321-322 STRING$ Fn 94, 323 String constants 46, 47 Strings 44, 46-47, 49, 136, 185-186,196, 197, 295 String space 167 String variables 47, 49 Subroutines 105, 140, 172, 229, 294, 333 Subtraction 52 SWAP St 91, 324 Syntax 8 SYSTEM St 91, 325

TAB Fn 94, 326 TAN Fn 94, 327 Tang en t 327 TERM St 91 Terms 8, 86 Text mode 80, 123, 303-304,339 Tiling 251-252 Time 328-329, 330 setting 328-329 trapping 240-241 TIME$ Fn 94, 328-329 TIMER Fn 94, 285, 330 TIMER/Trap St 91, 240-241, 331 Tracer 332 Trap pi n g communication 124-125,226-227 errors 156, 157, 228 joystick 238-239, 321-322 keys 192-193,232-233 light pen 234, 260 music 236-237, 265 timer 240-241, 331 TROFF St 91, 332 TRON St 91, 332 Typing programs 27-28

User installed devices 361 Unary minus 51 USR Fn 94, 333, 355-356

406 Index

VAL Fn 94, 317, 334 Variables 47, 117, 198, 324, 335, 336, 357-358 classifying 47-49, 136 clearing 117 declaring 47-49, 136 numeric 47, 136 string 47, 136, 356 VARPTR Fn 94, 335 VARPTR$ Fn 94, 336 Video aspect ratio 77-78 Video, clear 120 Video display worksheet 389 Video memory 79-80, 117-118, 257 Video pages 79-80, 117-118, 257 Video resolution 77-78 VIEW St 91, 337-338 Viewports 337-338 VIEW PRINT St 91, 339

WAIT St 91, 340 WEND St 91, 341 WHILE/WEND St 91, 341 WIDTH St 91, 342-344 Wildcards 13-14 WINDOW St 91, 345-346 World coordinates 266, 267, 345-346 WRITE St 91, 347 WRITE# St 91, 348

XOR 54

407