Jump to content

Applesoft BASIC

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Ylee (talk | contribs) at 02:13, 20 October 2016 (Background: wl). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Applesoft BASIC
Original author(s)Marc McDonald and Ric Weiland
Initial release1977; 47 years ago (1977)
Stable release
Applesoft II / 1978; 46 years ago (1978)
Operating systemApple II series
TypeMicrosoft BASIC

Applesoft BASIC is a dialect of Microsoft BASIC, developed by Marc McDonald and Ric Weiland, supplied with the Apple II series of computers. It supersedes Integer BASIC and is the BASIC in ROM in all Apple II series computers after the original Apple II model. It is also referred to as FP BASIC (from "floating point") because of the Disk Operating System (DOS) command used to invoke it, instead of INT for Integer BASIC. Applesoft BASIC was supplied by Microsoft and its name is derived from the names of both Apple and Microsoft. Apple employees, including Randy Wigginton, adapted Microsoft's interpreter for the Apple II and added several features. The first version of Applesoft was released in 1977 only on cassette tape and lacked proper support for high-resolution graphics. Applesoft II, which was made available on cassette and disk and in the ROM of the Apple II Plus and subsequent models, was released in 1978. It is this latter version, which has some syntax differences from the first as well as support for the Apple II high-resolution graphics modes, that most people mean by the term "Applesoft."

Background

When Steve Wozniak wrote Integer BASIC for the Apple II, he did not implement support for floating point math because he was primarily interested in writing games, a task for which integers alone were sufficient.[1] In 1976, Microsoft had developed Microsoft BASIC, a BASIC interpreter for the MOS Technology 6502, but at the time there was no production computer that used it. Upon learning that Apple had a 6502 machine, Microsoft asked if the company were interested in licensing BASIC, but Steve Jobs replied that Apple already had one. The Apple II was unveiled to the public at the West Coast Computer Faire in April 1977 and became available for sale in June. One of the most common customer complaints about the computer was BASIC's lack of floating-point capability. Integer BASIC is limited to whole numbers between −32768 and 32767 and caused problems for users attempting to write business applications with it. As Wozniak—the only person who understood Integer BASIC well enough to add floating point features—was busy with the Disk II drive and controller and with Apple DOS, Apple turned to Microsoft. Making things more problematic was that the rival TRS-80 and Commodore PET both had floating point-capable BASICs from the beginning. The Applesoft license also saved Microsoft from near-bankruptcy when they licensed BASIC to Commodore for the PET in an agreement that proved unexpectedly costly for them.

Apple reportedly obtained an eight-year license for Applesoft BASIC from Microsoft for a flat fee of $31,000, renewing it in 1985 through an arrangement that gave Microsoft the rights and source code for Apple's Macintosh version of BASIC.[2] Applesoft was designed to be backwards-compatible with Integer BASIC and uses the core of Microsoft's 6502 BASIC implementation, which includes using the GET command for detecting key presses and not requiring any spaces on program lines. While Applesoft BASIC is slower than Integer BASIC, it has many features that the older BASIC lacks:

  • Atomic strings: A string is no longer an array of characters (as in Integer BASIC and C); it is instead a garbage-collected object (as in Scheme and Java). This allows for string arrays; DIM A$(10) resulted in a vector of eleven string variables numbered 0–10.
  • Multidimensional arrays (numbers or strings)
  • Single-precision floating point variables with an 8-bit exponent and a 31-bit significand and improved math capabilities, including trigonometry and logarithmic functions
  • Commands for high-resolution graphics
  • DATA statements, with READ and RESTORE commands, for representing numerical and string values in quantity
  • CHR$, STR$, and VAL functions for converting between string and numeric types (both languages did have the ASC function)
  • User-defined functions: simple one-line functions written in BASIC, with a single parameter
  • Error-trapping, allowing BASIC programs to handle unexpected errors by means of a subroutine written in BASIC

Conversely, Applesoft lacked the MOD (remainder) operator that had been present in Integer BASIC.

Adapting BASIC for the Apple II was a tedious job as Apple received a source listing for Microsoft 6502 BASIC which proved to be an extremely buggy mess and also required the addition of Integer BASIC commands. Since Apple had no 6502 assembler on hand, the dev team were forced to send the source code over the phone lines to Call Computer, an outfit that offered compiler services. This was an extremely tedious, slow process and after Call Computer lost the source code due to an equipment malfunction, one of the programmers, Cliff Huston, used his own IMSAI 8080 computer to cross assemble the BASIC source.[3]

Applesoft is very similar to Commodore's BASIC 2.0 aside from features inherited from Integer BASIC. There are a few minor differences such as Applesoft's lack of bitwise operators; otherwise most BASIC programs that do not utilize hardware-dependent features will run on both BASICs.

Microsoft licensed a BASIC compatible with Applesoft to VTech for its Laser 128 clone.[4]

Speed issues, features

Whereas Wozniak originally referred to his Integer BASIC as "Game BASIC" (having written it so he could write a Breakout clone for his new computer),[1] few action games were written in Applesoft BASIC for several reasons.

In that era of carefully counting clock cycles and limited memory, it was inefficient to write speed-dependent programs that ran on a runtime interpreter. The use of "real" (floating-point) numbers for all math operations created unnecessary overhead and degraded performance. A common feature of all Microsoft 6502 BASICs is the lack of double-precision variables or true integer math.

BASIC normally always works in single-precision and although a % can be placed after a variable to mark it as integer, its value would merely be converted back into single-precision, slowing down program execution and wasting memory (as each "%" required one extra byte of code). The integer variable type on Microsoft 6502 BASIC was really only designed for arrays because each element would take two bytes (versus, in the case of Applesoft, five for floating-point).

Additionally, shape tables were a slow alternative to bitmaps. Shape tables were usually even larger than their respective bitmaps in the amount of bit space they consumed. No provision existed for mixing text and graphics, except for the limited "hardware split screen" of the Apple II (four lines of text at the bottom of the screen). Many graphics programs thus contained their own bitmap character generator routines. No provision was added in the 128 kB Apple IIe and Apple IIc models' BASIC interpreters for the new machines' extra memory and double-resolution graphics, or for the Apple IIGS's 16-color mode. Beagle Bros offered machine-language workarounds for these problems.

Applesoft BASIC programs were stored as a linked list of lines; a GOTO or GOSUB took O(n) (linear) time, and although Applesoft programs were not very long compared to today's software, on a 1 MHz 6502 this could create a significant bottleneck. Large programs were often written with the most-used subroutines at the top of the program to reduce the processing time for GOSUB calls.

Furthermore, there was no sound support – aside from a PEEK command that can be used to click the speaker. One can also PRINT an ASCII bell character to sound the system alert beep. The language is not fast enough to produce more than a baritone buzz from repeated clicks anyway. Music spanning several octaves can be played by repeated calls to a machine-language tone generator.

Applesoft lacks several commands and functions common to most of the non-6502 Microsoft BASIC interpreters, such as:

  • INSTR (search for a substring in a given string)
  • PRINT USING (formatting numbers in printed output)
  • INKEY$ (check for a keypress without stopping the program) although a PEEK location did provide this functionality.
  • LPRINT (output printed content to a printer instead of the screen)

Applesoft BASIC can only be extended by two means: the ampersand (&) command and the USR() function. These are two features that called machine-language routines stored in memory. Routines that need to be fast or require direct access to arbitrary functions or data in memory can thus be called from a higher-level interpreted BASIC program. The USR() function takes one numerical argument, and can be programmed to derive and return a calculated function value, to be used in a numerical expression. "&" was effectively a shorthand for CALL, with an address that would be predefined.

The 1978 Applesoft II Manual essentially ignored the & command, merely listing it among reserved words in an appendix, and stating, "The ampersand ( & ) is intended for the computer's internal use only; it is not a proper APPLESOFT command. This symbol, when executed as an instruction, causes an unconditional jump to location $3F5. Use Reset Ctrl+C Return to recover", referring to the command's "hook" address.[5]

The 1982 Applesoft manual for the Apple IIe (also in an appendix) did not call it "improper", and said slightly more about it, adding to the "internal use" clause, "...and for user-supplied machine-language routines", but giving no further documentation beyond describing the hook address.[6] In practice it was possible for an ampersand routine to parse code and arguments that followed the & character by calling routines in the BASIC ROM.

Applesoft, like Integer BASIC before it, does not come with any built-in commands for dealing with files or disks, other than a feature to save programs to, and load programs from, cassette tape. The Apple II disk operating system, known simply as DOS, augments the language to provide such abilities.

Unlike in Integer BASIC, Applesoft BASIC variable names are significant only to two letters; they can be made longer, but only the first two letters are used. For instance, "LOW" and "LOSS" are treated as the same variable, and attempting to assign a value to "LOSS" overwrites any value assigned to "LOW." Furthermore, because the language used tokenization, a programmer has to avoid using any consecutive letters that are also Applesoft commands or operations (one cannot use the name "SCORE" for a variable because it interprets the OR as a Boolean operator, thus rendering it SC OR E, nor can one use "BACKGROUND" because the command "GR" invokes the low-resolution graphics mode, in this case creating a syntax error).

The Apple II high-resolution graphics mode is extremely limited; a user is limited to six colors (black, green, violet, orange, blue, and white), two of which do not appear in odd-numbered columns and two that do not appear in even-numbered ones; and white was a combination of two neighboring pixels, supplanting the individual pixel colors. A hardware hack incorporated into the Apple IIe's 80-column character card expands the mode to higher horizontal resolution and opens up the availability of all 16 colors of the lo-res graphics mode. To its benefit, the language allows for easy use of vector graphics, a feature unavailable in the lower-resolution graphics mode.

A deficiency in Applesoft's error-trapping with ONERR means that the system stack would not be reset if an error-handling routine did not invoke RESUME, potentially leading to a crash. Error-handling that does not employ RESUME can avoid the problem with a CALL -3288 or (equivalent) 62248 before exiting the routine.[6]

Through several early models of the Apple II, Applesoft BASIC does not support the use of lowercase letters in programs, except in strings. (Thus, Applesoft can display lowercase letters, but cannot recognize them as part of a program; thus, PRINT is a valid command but print and Print are unrecognizable and result in a syntax error.)

Bugs

Due to a short-cut in the programming of the overflow test when evaluating 16 bit numbers, entering any number from 437760 to 440319 for a new line number at the BASIC prompt will cause Applesoft to crash, usually to a monitor prompt.[7] Entering 440000 at the prompt has been used to hack games that are protected against entering commands at the prompt after the program is loaded.

Early evolution

The original Applesoft, stored in RAM as documented in its Reference Manual of November 1977, has smaller interpreter code than the later Applesoft II, occupying 8½ kb of memory,[8] instead of the 10 kb used by the later Applesoft II. Consequently, it lacks a number of command features developed for the later, mainstream version:

  • All commands supporting Apple's "high resolution" graphics (9 total)
  • Error-trapping with ONERR...GOTO and RESUME
  • Machine-routine shorthand call "&"
  • Screen-clearing HOME (a call to a system ROM routine)
  • Text-output control NORMAL, INVERSE, FLASH and SPEED=
  • The print-space function SPC() is listed among reserved words in the manual, but is not otherwise documented (the TAB() print-function is documented)
  • Cassette tape storage of numerical arrays: STORE and RECALL
  • Device response: WAIT

as well as several the later version would have, that had already been present in Apple's Integer BASIC:

  • Program-line deletion: DEL
  • Machine-routine access: CALL
  • Peripheral device access: IN# and PR# (although IN without "#" is listed among reserved words)
  • Memory range control: HIMEM: and LOMEM:
  • Execution tracking for debugging: TRACE and NOTRACE
  • Screen-positioning: HTAB and VTAB
  • Subroutine aborting POP
  • Functions PDL() to read the analog controllers, and SCRN() to read the low-resolution graphics screen (both accessing system ROM routines)

In addition, its low-resolution graphics commands have different names from their Integer BASIC/Applesoft II counterparts. All command names are of the form PLTx such that GR, COLOR=, PLOT, HLIN and VLIN are called PLTG, PLTC, PLTP, PLTH, and PLTV, respectively. The command for returning to text mode, known as TEXT in other versions, is simply TEX, and carries the proviso that it has to be the last statement in a program line.

The USR() function is also defined differently, serving as a stand-in for the absent CALL command. Its argument is not for passing a numerical value to the machine-language routine, but is instead the call-address of the routine itself; there is no "hook" to pre-define the address. All of several examples in the manual use the function only to access "system monitor ROM" routines, or short user-routines to manipulate the ROM routines. No mention is made of any code to calculate the value returned by the function itself; the function is always shown being assigned to "dummy" variables, which, without action to set a value by user-code, just receive a meaningless value handed back to them. Even accessed ROM routines that return values (in examples, those that provide the service of PDL() and SCRN() functions) merely have their values stored, by user-routines, in locations that are separately PEEKed in a subsequent statement.

Unlike in Integer BASIC and Applesoft II, the Boolean operators AND, OR and NOT perform bitwise operations on 16-bit integer values. If they are given values outside that range, an error results.

The terms OUT and PLT (and the aforementioned IN) appear in the list of reserved words, but are not explained anywhere in the manual.

Sample code

Hello World, with inverse video and bell character, run then listed

Hello World in Applesoft BASIC can be entered as the following:

 10TEXT:HOME
 20?"HELLO WORLD"

Multiple commands can be included on the same line of code if separated by a colon (:). The ? can be used in Applesoft BASIC (and almost all versions of Microsoft BASIC) as a shortcut for "PRINT", though spelling out the word is not only acceptable but canonical—Applesoft converted "?" in entered programs to the same token as "PRINT" (thus no memory is actually saved by using "?"), thus either appears as "PRINT" when a program is listed. The program above appears in a LIST command as:

 10  TEXT : HOME
 20  PRINT "HELLO WORLD"

[9]

When Applesoft II BASIC was initially released in mid-1978, it came on cassette tape and could be loaded into memory via the Apple II's machine language monitor. When the enhanced Apple II+ replaced the original II in 1979, Applesoft was now included in ROM and automatically started on power-up if no bootable floppy disk was present. Conversely, Integer BASIC was now removed from ROM and turned into an executable file on the DOS 3.3 disk.

BASIC for the Apple III

Microsoft and Apple each developed their own versions of BASIC for the Apple III computer. Apple III Microsoft BASIC was designed to run on the CP/M platform available for the Apple III. Apple Business BASIC, meanwhile, shipped with the Apple III. Donn Denman ported Applesoft BASIC to SOS and reworked it to take advantage of the extended memory of the Apple III.

Both languages introduced a number of new or improved features over Applesoft II, some of the same features as each other, and some unique to each. Both languages replace Applesoft II's single-precision floating-point variables using 5-byte storage with the somewhat-reduced-pecision 4-byte variables, while also adding a larger numerical format. Apple III Microsoft BASIC provides double-precision floating-point variables, taking 8 bytes of storage,[10] while Apple Business BASIC offers an extra-long integer type, also taking 8 bytes for storage.[11] Both languages also retain 2-byte integers, and maximum 255-character strings.

Other new features common to both languages include:

  • Incorporation of disk-file commands within the language.
  • Operators for MOD and for integer-division.
  • An optional ELSE clause in IF...THEN statements.
  • HEX$() function for hexadecimal-format output.
  • INSTR function for finding a substring within a string.
  • PRINT USING statement to control format of output. Apple Business BASIC had an option in addition to directly specifying the format with a string expression, of giving the line number where an IMAGE statement gave the formatting expression, similar to a FORMAT statement in FORTRAN.

Differences of the same features:

Apple III Microsoft BASIC Apple Business BASIC
integer division operator \ (backslash) DIV
reading the keyboard without waiting INKEY$ function returns a one-character string representing the last key pressed, or the null string if no new key pressed since last reading KBD read-only "reserved variable" returns the ASCII code of the last key pressed; the manual fails to document what is returned if no new key pressed since last reading
reassigning a portion of a string variable MID$() assignment statement SUB$() assignment statement
determining position of text output POS() function to read horizontal screen position, and LPOS() function to read horizontal position on printer HPOS and VPOS assignable "reserved variables" to read or set the horizontal or vertical position for text screen output
accepting hexadecimal-format values "&H"-formatted expressions TEN() function to give numerical value from string representing hexadecimal
result of ASC("")

(null string operand)

causes an error returns the value −1

Features specific to each language are described separately below.

Apple III Microsoft BASIC additional new features

  • INPUT$() function to replace Applesoft's GET command.
  • LINE INPUT statement to input an entire line of text, regardless of punctuation, into a single string variable.
  • LPRINT and LPRINT USING statements to automatically direct output to paper.
  • LSET and RSET statements to left- or right-justify a string expression within a given string variable's character length.
  • OCT$() function for output, and "&"- or "&O"-formatted expressions, for manipulating octal notation.
  • SPACE$() function for generating blank spaces outside of a PRINT statement, and STRING$() function to do likewise with any character.
  • WHILE...WEND statements, for loop structures built on general Boolean conditions without an index variable.
  • Bitwise Boolean (16-bit) operations (AND, OR, NOT), with additional operators XOR, EQV, IMP.
  • Line number specification in the RESTORE command.
  • RESUME options of NEXT (to skip to the statement after that which caused the error) or a specified line number (which replaces the idea of exiting error-handling by GOTO-line, thus avoiding Applesoft II's stack error problem).
  • Multiple parameters in user-defined (DEF FN) functions.
  • A return to the old Applesoft One concept of having multiple USR() functions at different addresses, by establishing ten different USR functions, numbered USR0 to USR9, with separate DEF USRx statements to define the address of each. The argument passed to a USRx function can be of any specific type, including string. The returned value can also be of any type, by default the same type as the argument passed.

There is no support for graphics provided within the language, nor for reading analog controls or buttons; nor is there a means of defining the active window of the text screen.

Apple Business BASIC additional new features

Apple Business BASIC eliminates all references to absolute memory addresses. Thus, the POKE command and PEEK() function were not included in the language, and new features replaced the CALL statement and USR() function. Functionality of certain features in Applesoft that had been achieved with various PEEK and POKE locations is now provided by:

  • BUTTON() function to read game-controller buttons
  • WINDOW statement to define the active window of the text screen by its coordinates
  • Aforementioned KBD, HPOS, and VPOS system variables

External binary subroutines and functions are now loaded into memory by a single INVOKE disk-command that loads separately-assembled code modules, listing the names of all files to be used. A PERFORM statement is then used to call an INVOKEd procedure by name, with an argument-list. INVOKEd functions would be referenced in expressions by EXFN. (floating-point) or EXFN%. (integer), with the function name appended, plus the argument-list for the function.

Graphics are supported with an INVOKEd module, with features including displaying text within graphics in various fonts, within four different graphics modes available on the Apple III, including the precursor of Apple IIe's double-high-resolution mode.

See also

References

  1. ^ a b Wozniak, Steve (2014-05-01). "How Steve Wozniak Wrote BASIC for the Original Apple From Scratch". Gizmodo. Retrieved 2 May 2014.
  2. ^ Herzfeld, Andy "MacBasic – The Sad Story of MacBasic". http://www.folklore.org/StoryView.py?project=Macintosh&story=MacBasic.txt . Folklore.org. 2014 February 12
  3. ^ "History of the Apple II - Chapter 16 - Languages". Retrieved July 6, 2016.
  4. ^ Grevstad, Eric (1986-12). "Laser 128 / An Affordable Compatible". inCider. p. 58. Retrieved 29 June 2014. {{cite news}}: Check date values in: |date= (help)
  5. ^ Applesoft II Basic Programming Reference Manual, Apple Computer, Inc., 1978
  6. ^ a b Applesoft BASIC Programmer's Reference Manual (for IIe only), Apple Computer, Inc., 1982
  7. ^ http://www.txbobsc.com/scsc/scdocumentor/D912.html Disassembled ROM. See comments at $DA1E.
  8. ^ Applesoft Extended Precision Floating Point Basic Language Reference Manual, Apple Computer, Inc., November 1977
  9. ^ This article includes text from Everything2, licensed under GFDL.
  10. ^ Apple III Microsoft BASIC Reference Manual, Microsoft Corporation, 1982
  11. ^ Apple Business BASIC Reference Manual, Apple Computer, Inc., 1981