RADIO SHACK–STYLE WEB REFERENCE

TRS-80
MODEL 4
BASIC

PROGRAMMER'S REFERENCE MANUAL
Web Emulator Expanded Edition • Arrays • Shared/Local Virtual Drives • Disk & Server-Backed Tape File I/O • Reel-to-Reel/Cassette Emulation • RENUM • PRINT USING • Clipboard • Command History • Line Editing • Interruptible BREAK
Detailed Command, Function, Math, String, Operator, and Programming Reference
RETURN TO EMULATORRETURN TO MAIN

Table of Contents

01Welcome to Model 4 BASIC02How to Use This Manual03Starting the Emulator04The READY Prompt05Entering and Editing Program Lines06Direct Mode and Program Mode07RUN08BREAK Program Interrupt09LIST10NEW11CLEAR12CLS13HELP, MEM, DIR, CATALOG, BASIC, SYSTEM14Loading ASCII BASIC Programs15Saving ASCII BASIC Programs16ASCII File Format17PRINT18PRINT with Semicolons19PRINT with Commas20TAB(N)21PRINT @ Position22INPUT23LET and Assignment24REM Comments25END26Multiple Statements with Colon27GOTO28IF...THEN29Comparison Operators30GOSUB and RETURN31FOR...NEXT32STEP33Nested Loops34PAUSE35DATA36READ37RESTORE38Numeric Variables39String Variables40DIM Overview41One-Dimensional Arrays42Multidimensional Arrays43String Arrays44Array Subscripts45Array Errors46Arithmetic Operators47Logical Operators48ABS, INT, FIX, ROUND, SGN49SQR, EXP, LOG50SIN, COS, TAN51ASN, ACS, ATN52MIN and MAX53Factorial54RND and RANDINT55PI, E, TRUE, FALSE56LEN, ASC, VAL57CHR$ and STR$58LEFT$, RIGHT$, MID$59UPPER$, LOWER$, TRIM$60INKEY$61Operator Precedence62Screen Geometry63Character Graphics64Animation65Debugging with PRINT66Debugging GOTO Programs67Debugging Arrays68Avoiding Infinite Loops69Program Structure70Performance and Browser Pacing71Compatibility Notes72Error: ?SN ERROR73Runtime Error Reference74Program: Horizontal Counter75Program: Dice Roller76Program: Guessing Game77Program: Multiplication Table78Program: Prime Number Test79Program: Array Squares80Program: Matrix Fill81Program: String Array Menu82Program: Moving Star83Program: Random Histogram84Program: Data Reader85Program: Subroutine Demonstration86Program: One-Dimensional Life87Adapting Historical Listings88Backing Up Your Programs89Using Notepad++90Mobile and iPad Use91Keyboard Shortcuts92Quick Command Summary93Quick Function Summary94Alphabetical Index A–G95Alphabetical Index H–P96Alphabetical Index Q–Z97Final Notes98INSTR String Search99String Comparisons in IF...THEN100REM and Colon Handling101Enhanced Runtime Error Diagnostics102Persistent Virtual Drive 0103Command History, Line Editing, and EDIT104Virtual Disk Backup and Restore105Shared Server Drive 0106Local Browser Drive 1107OPEN and File Numbers108PRINT # Sequential Output109INPUT # Sequential Input110LINE INPUT #111EOF() and CLOSE112File I/O Programming Examples113Clipboard, Paste, and Program Copy114Current Compatibility and Feature Summary115TYPE Command116COPY Between Virtual Drives117PC to Virtual Drive: PUT / IMPORT118Virtual Drive to PC: GET / EXPORT119Binary and Non-BASIC Files120CR/LF and Current Command Summary121Level II BASIC Compatibility122REM and Colon Parsing123INPUT, CLEAR, DEFINT and DEFDBL124STR$, Logical Conditions and NEXT125INKEY$ and TRS-80 Graphics Characters126TAB() and BIORHYTHM Compatibility127DATE$ and TIME$128Tape System Overview129CLOAD and CSAVE130Tape Catalog, Position, Rewind, Stop, and Eject131BASIC Tape Data Files132Tape Data I/O Examples133RENUM Program Renumbering134RENUM Branch-Target Rules and Examples135PRINT USING136Current Emulator Command Checklist
Expanded edition: Command, function, array, operator, mathematical, string, screen, disk, tape, renumbering, file, and execution entries now include purpose, syntax, parameters, detailed behavior, guidance, errors, related entries, and the original runnable examples.
Compatibility notice: this manual describes the web emulator. It is inspired by the TRS-80 Model 4 but is not an archival reproduction of a copyrighted historical manual.
TRS-80 MODEL 4 BASICPAGE 1

Welcome to Model 4 BASIC

This manual documents the web-based TRS-80 Model 4 TinyBASIC Fully Loaded emulator. It is written in the style of an early-1980s computer reference, but it accurately describes the features implemented by this browser emulator. The system accepts numbered BASIC program lines, direct commands, numeric and string expressions, arrays, DATA statements, subroutines, loops, screen-positioned output, and ASCII program files. Use the emulator as a programming laboratory: type a line, list it, run it, interrupt it, modify it, and save it back to your local computer.

PRINT "RADIO SHACK TRS-80 MODEL 4"
PRINT "READY"
Contents1 / 136
TRS-80 MODEL 4 BASICPAGE 2

How to Use This Manual

The manual is organized as a tutorial, command reference, programming guide, troubleshooting handbook, and collection of runnable examples. Use the search box at the top to locate a statement such as DIM, PRINT, BREAK, RND, or GOSUB. The table of contents links to each page. Printed output is formatted as a multi-page reference manual. Features marked as emulator extensions are convenient browser features and are not claimed to be exact copies of every historical Model 4 BASIC implementation.

Contents2 / 136
TRS-80 MODEL 4 BASICPAGE 3

Starting the Emulator

Open the emulator page and allow the simulated boot sequence to complete. Click or tap the green display before typing. The READY prompt indicates that the command processor is waiting. A line that begins with a number is stored in program memory. A line without a number is executed immediately as a direct command. RESET / BOOT clears the display and restarts the simulated system; it does not represent a physical power cycle.

10 PRINT "HELLO"
20 END
RUN
Contents3 / 136
TRS-80 MODEL 4 BASICPAGE 4

The READY Prompt

The greater-than prompt is the input point. Direct statements are useful for calculations and experiments. Numbered lines build a program. LIST displays the stored program. RUN begins execution at the lowest numbered line. NEW removes all program lines. CLEAR resets variables and runtime stacks but leaves the program text intact.

PRINT 2+2
A=25
PRINT SQR(A)
Contents4 / 136
TRS-80 MODEL 4 BASICPAGE 5

Entering and Editing Program Lines

Type a line number followed by a BASIC statement. Re-entering the same number replaces the old line. Entering a number by itself deletes that line. Program lines are sorted numerically, so you may enter them in any order. Leave gaps such as 10, 20, 30 so additional lines can be inserted later. The current emulator also provides cursor-aware command-line editing: Left/Right move through the line, Home/End jump to either end, Backspace and Delete remove characters, and normal typing inserts characters at the cursor. EDIT n recalls stored BASIC line n onto this editable command line.

10 PRINT "FIRST"
30 PRINT "THIRD"
20 PRINT "SECOND"
LIST
20
Contents5 / 136
TRS-80 MODEL 4 BASICPAGE 6

Direct Mode and Program Mode

Direct mode executes an unnumbered statement immediately. Program mode stores numbered lines for later execution. Most statements work in either mode, although GOTO and GOSUB require a stored program target. Direct mode is especially useful for testing expressions, checking functions, and inspecting variables.

PRINT FACT(6)
PRINT SIN(PI/2)
PRINT RANDINT(1,6)
Contents6 / 136
TRS-80 MODEL 4 BASICPAGE 7

RUN

RUN resets runtime variables and arrays, scans DATA statements, clears FOR/NEXT and GOSUB stacks, and begins execution at the first stored line. When the program reaches END or passes the final statement, READY is displayed. A running program can be stopped with BREAK PROGRAM, the on-screen BREAK key, Esc, or Ctrl+C.

Purpose

Starts execution of the numbered BASIC program currently stored in emulator memory.

Syntax

RUN

Parameters and Elements

ElementDescription
RUNDirect command; it does not take a line-number argument in this emulator.

Detailed Description

RUN prepares a fresh execution environment, clears scalar variables and arrays, resets DATA, FOR/NEXT, and GOSUB state, scans DATA statements, and begins with the lowest numbered program line. Program text remains unchanged. Execution ends normally after END or after the final statement, and it can be interrupted by BREAK.

Programming Guidance

  • Use LIST before RUN after loading or editing a program.
  • Save important changes before experimenting with NEW or reloading another file.
  • Use PAUSE in animation loops so output remains readable and the browser stays responsive.

Common Errors and Limitations

  • RUN reports that no program is in memory when there are no numbered lines.
  • A runtime syntax, array, branch, arithmetic, or DATA error stops execution and displays an error message.

Related Entries

Examples

The original runnable examples are retained below.

10 PRINT "RUNNING"
20 GOTO 10
RUN
Contents7 / 136
TRS-80 MODEL 4 BASICPAGE 8

BREAK Program Interrupt

BREAK is the emergency stop for a running BASIC program. The large BREAK PROGRAM button, the virtual BREAK key, Esc, and Ctrl+C all request an interrupt. The interpreter checks for the interrupt between statements and while pacing long loops or PAUSE delays. BREAK also cancels a program waiting at INPUT. The display reports *** BREAK *** followed by READY. BREAK does not erase the stored program.

Purpose

Stops a running program without erasing its numbered lines.

Syntax

BREAK PROGRAM buttonVirtual keyboard: BREAKKeyboard: EscKeyboard: Ctrl+C

Parameters and Elements

ElementDescription
BREAK requestAn interrupt flag checked between statements, during paced loops, during PAUSE, and while INPUT is waiting.

Detailed Description

BREAK is the emergency recovery mechanism for an accidental infinite loop or a program that is producing excessive output. It clears active runtime stacks and cancels pending input. The stored listing stays available for inspection, correction, and another RUN.

Programming Guidance

  • Use BREAK rather than refreshing the browser, because refreshing can discard an unsaved program.
  • After a break, use LIST and add temporary PRINT statements to locate the loop or branch responsible.
  • A very large single mathematical calculation may not stop until that calculation returns; normal BASIC loops are interruptible.

Common Errors and Limitations

  • BREAK is not an error and does not remove the program.
  • Pressing BREAK while no program is running simply clears the current input line in some interface contexts.

Related Entries

Examples

The original runnable examples are retained below.

10 PRINT "PRESS BREAK"
20 GOTO 10
RUN
Contents8 / 136
TRS-80 MODEL 4 BASICPAGE 9

LIST

LIST displays every stored line in ascending numeric order. The listing is plain ASCII text and corresponds to what SAVE ASCII BASIC writes to disk. LIST does not run the program or alter variables. Use it often while debugging to verify line numbers, punctuation, array subscripts, and branch targets.

Purpose

Displays every stored numbered program line in ascending numeric order.

Syntax

LIST

Detailed Description

LIST is the principal program-inspection command. It shows exactly the text that will be written by SAVE ASCII BASIC. Listing does not execute statements, change variables, or reset arrays.

Programming Guidance

  • Verify branch targets and quotation marks after importing a program.
  • Use line-number gaps such as 10, 20, and 30 to make later insertion easier.

Common Errors and Limitations

  • LIST displays a no-program message when memory contains no numbered lines.

Related Entries

Examples

The original runnable examples are retained below.

Contents9 / 136
TRS-80 MODEL 4 BASICPAGE 10

NEW

NEW removes all numbered program lines. It is intended for starting a new program. Save any program you wish to keep before issuing NEW. NEW does not delete files from the local computer; it only clears the emulator program memory.

Purpose

Deletes all numbered BASIC lines from emulator memory so a new program can be entered.

Syntax

NEW

Detailed Description

NEW affects the in-memory program only. It does not delete a previously saved .BAS file. Because browsers do not provide automatic recovery of unsaved BASIC listings, NEW should be used only after the current program has been saved or is no longer needed.

Programming Guidance

  • Use SAVE ASCII BASIC before NEW when the listing has value.
  • Use CLEAR instead when only variables and runtime state need to be reset.

Common Errors and Limitations

  • There is no undo command after NEW.

Related Entries

Examples

The original runnable examples are retained below.

Contents10 / 136
TRS-80 MODEL 4 BASICPAGE 11

CLEAR

CLEAR resets numeric variables, string variables, numeric arrays, string arrays, the DATA pointer, FOR/NEXT stack, and GOSUB stack. The numbered program remains in memory. RUN performs its own runtime reset before execution, so CLEAR is most useful while experimenting in direct mode.

Purpose

Resets variables, arrays, DATA position, and active runtime stacks while preserving program text.

Syntax

CLEAR

Detailed Description

CLEAR initializes A through Z to zero, A$ through Z$ to empty strings, removes array definitions and values, resets the DATA pointer, and empties FOR/NEXT and GOSUB stacks. RUN performs a comparable runtime reset automatically.

Programming Guidance

  • Use CLEAR during direct-mode testing when previous values may affect results.
  • Do not use CLEAR inside a program after DIM unless you intend to remove the arrays.

Common Errors and Limitations

  • Array references made after CLEAR require DIM again.

Related Entries

Examples

The original runnable examples are retained below.

Contents11 / 136
TRS-80 MODEL 4 BASICPAGE 12

CLS

CLS clears the emulated display. Used as a program statement, it creates a clean screen before menus, games, tables, or animation. Used as a direct command, it clears the terminal and restores the prompt.

Purpose

Clears the simulated terminal or screen display.

Syntax

CLS10 CLS

Detailed Description

In direct mode, CLS clears the terminal and restores the command prompt. In program mode, it clears output so menus, positioned text, or animation can begin with a clean display. CLS does not modify program lines or variables.

Programming Guidance

  • Place CLS near the beginning of display-oriented programs.
  • Frequent CLS in a fast loop may flicker; PRINT @ can update selected positions more smoothly.

Related Entries

Examples

The original runnable examples are retained below.

10 CLS
20 PRINT @ 128,"MODEL 4 BASIC"
Contents12 / 136
TRS-80 MODEL 4 BASICPAGE 13

HELP, MEM, DIR, CATALOG, BASIC, SYSTEM

HELP prints a compact list of implemented statements, operators, functions, arrays, disk/tape controls, file I/O, RENUM, and BREAK methods. MEM reports simulated free memory. DIR and CATALOG enumerate the currently selected virtual drive, as does FILES. BASIC and SYSTEM display period-style ready messages. These commands provide emulator conveniences and do not constitute a complete TRSDOS implementation.

Purpose

Provides emulator help and period-style simulated system information.

Syntax

HELPMEMDIRCATALOGBASICSYSTEM

Parameters and Elements

ElementDescription
HELPDisplays supported commands, functions, arrays, file controls, and interrupt keys.
MEMReports simulated free memory; the figure is decorative rather than a live JavaScript heap measurement.
DIR / CATALOGDisplays a simulated drive directory.
BASIC / SYSTEMDisplays Model 4 BASIC or TRSDOS-style ready messages.

Detailed Description

These commands support the atmosphere and usability of the emulator. They do not implement a complete TRSDOS file system, disk allocation map, or machine-language command environment.

Common Errors and Limitations

  • DIR and CATALOG enumerate the emulator's selected virtual drive, not arbitrary folders on the user's PC, iPad, or server.
  • MEM should not be used to estimate actual browser memory consumption.

Related Entries

Examples

The original runnable examples are retained below.

Contents13 / 136
TRS-80 MODEL 4 BASICPAGE 14

Loading ASCII BASIC Programs

Select LOAD ASCII BASIC and choose a local .BAS or .TXT file. The browser reads the file as text, normalizes line endings, and imports numbered BASIC lines into program memory. The file never needs to be uploaded to a server. After loading, use LIST to inspect it and RUN to execute it. A valid ASCII program should contain one numbered BASIC line per text line.

Purpose

Imports a plain-text BASIC listing from the local device into emulator program memory.

Syntax

Select LOAD ASCII BASICChoose a plain-text file containing numbered BASIC lines

Parameters and Elements

ElementDescription
.BAS / .TXT / other text fileThe filename extension is not part of the BASIC language; the file contents must be readable text.
Numbered lineA line beginning with a decimal line number is stored in the program.

Detailed Description

The browser File API reads the selected file locally; the program is not uploaded to a remote server. Line endings are normalized and numbered lines are inserted into memory. On iPadOS, custom .BAS extensions may be greyed out if the file input restricts recognized types; an unrestricted file picker or a temporary .TXT filename avoids that problem.

Programming Guidance

  • After loading, issue LIST before RUN.
  • Use straight ASCII quotation marks rather than typographic quotes.
  • Keep a copy of the original file before adapting a historical listing.

Common Errors and Limitations

  • Unnumbered lines are not stored as program lines.
  • Rich-text documents, word-processing files, and binary tokenized BASIC files are not plain ASCII listings.

Related Entries

Examples

The original runnable examples are retained below.

10 PRINT "LOADED FROM LOCAL PC"
20 END
Contents14 / 136
TRS-80 MODEL 4 BASICPAGE 15

Saving ASCII BASIC Programs

Select SAVE ASCII BASIC to download the current program as a plain-text .BAS file. Lines are saved in ascending order with their line numbers. The file can be edited with Notepad, Notepad++, VS Code, or another text editor, then loaded back into the emulator. Saving does not include current variable values, screen contents, or execution state.

Purpose

Downloads the current numbered listing as a portable plain-text BASIC file.

Syntax

Select SAVE ASCII BASIC

Detailed Description

The emulator sorts program lines numerically, joins them with text line endings, and asks the browser to download the result. Only source code is saved. Variables, arrays, screen output, current DATA position, and execution state are not included.

Programming Guidance

  • Use meaningful filenames after the browser download completes.
  • Store master copies in Files, iCloud Drive, OneDrive, or another backed-up location.
  • Plain ASCII files can be edited using Notepad++, VS Code, Textastic, or similar editors.

Common Errors and Limitations

  • An empty program cannot produce a useful listing.
  • Some mobile browsers choose their own download location or filename behavior.

Related Entries

Examples

The original runnable examples are retained below.

Contents15 / 136
TRS-80 MODEL 4 BASICPAGE 16

ASCII File Format

The portable program format uses ordinary printable characters and line endings. Avoid rich-text editors that may insert formatting or typographic quotation marks. Use straight double quotes around BASIC strings. A line without a leading number is not stored as part of a loaded program. Keep a backup before making large edits.

Purpose

Defines the portable, human-readable format used for loading and saving emulator programs.

Syntax

10 PRINT "HELLO"20 END

Parameters and Elements

ElementDescription
Line numberDecimal number at the beginning of each stored program line.
Statement textOne or more BASIC statements following the line number.
EncodingUTF-8 or ordinary ASCII-compatible plain text.

Detailed Description

The format is source text, not the tokenized binary representation used by some historical BASIC systems. Each physical text line should contain one numbered BASIC line. Colons may combine multiple statements within that line.

Programming Guidance

  • Use straight quotes, ordinary spaces, and standard line endings.
  • Avoid editors that silently replace quotes or insert formatting characters.

Common Errors and Limitations

  • A genuine tokenized TRS-80 .BAS disk image may require conversion before this emulator can read it.

Related Entries

Examples

The original runnable examples are retained below.

Contents16 / 136
TRS-80 MODEL 4 BASICPAGE 17

PRINT

PRINT displays strings, numeric expressions, variables, array elements, and function results. A bare PRINT outputs a blank line. Items can be separated by semicolons or commas. Numbers are formatted without unnecessary trailing zeros. Strings are printed exactly as evaluated.

Purpose

Writes text, numbers, variables, array elements, or expression results to the emulator display.

Syntax

PRINT "TEXT"PRINT expressionPRINT item1;item2PRINT item1,item2PRINT

Parameters and Elements

ElementDescription
itemA string expression, numeric expression, variable, array element, or supported function.
;Joins output without ordinary tab-zone spacing; a trailing semicolon suppresses the newline.
,Advances output toward the next print zone.
bare PRINTProduces a blank line or terminates a line previously held open.

Detailed Description

PRINT evaluates each item from left to right and converts numeric results to readable text. String literals appear without quotation marks. Array references and functions are evaluated exactly as they would be in assignments or conditions.

Programming Guidance

  • Use labels such as PRINT "I=";I when debugging.
  • Use PRINT @ for random-access character placement and TAB for column alignment.

Common Errors and Limitations

  • Unbalanced quotation marks or parentheses produce a syntax or expression error.
  • A reference to an undimensioned array causes an array error.

Related Entries

Examples

The original runnable examples are retained below.

PRINT "TOTAL=";A
PRINT X(I)
PRINT
Contents17 / 136
TRS-80 MODEL 4 BASICPAGE 18

PRINT with Semicolons

A semicolon joins output without automatically advancing to the next display line. It is useful for constructing tables, progress indicators, and rows of symbols. In this emulator, PRINT statements ending with a semicolon preserve the current output line for the next PRINT.

Purpose

Controls horizontal output by placing values directly next to one another and optionally suppressing the newline.

Syntax

PRINT "A";"B"PRINT I;" ";PRINT

Detailed Description

Semicolons are useful for rows, prompts, progress displays, and character graphics. A trailing semicolon leaves the current output line open. A later bare PRINT advances to the next line.

Programming Guidance

  • Add explicit spaces inside quoted strings when separation is desired.
  • Remember that numeric formatting may already include spacing depending on the emulator's formatter.

Common Errors and Limitations

  • Forgetting the final bare PRINT can cause later output to continue on the same line.

Related Entries

Examples

The original runnable examples are retained below.

10 FOR I=1 TO 10
20 PRINT I;" ";
30 NEXT I
40 PRINT
Contents18 / 136
TRS-80 MODEL 4 BASICPAGE 19

PRINT with Commas

A comma advances output toward the next tab zone. This resembles classic BASIC column formatting and is useful for aligned reports. Exact spacing depends on the current column and the emulator tab-zone width.

Purpose

Formats output in fixed-width print zones similar to classic BASIC report columns.

Syntax

PRINT "NAME","SCORE"PRINT A,B,C

Detailed Description

The emulator advances to the next 16-column zone based on the current output position. Commas are convenient for rough tables but do not guarantee alignment for values longer than a zone.

Programming Guidance

  • Use TAB(N) for explicit column targets.
  • Test long headings and negative numbers because they may cross a zone boundary.

Related Entries

Examples

The original runnable examples are retained below.

PRINT "NAME","SCORE"
PRINT "RICH",100
Contents19 / 136
TRS-80 MODEL 4 BASICPAGE 20

TAB(N)

TAB(N) inserts spaces until the output reaches column N. If the current column has already passed N, no reverse movement occurs. TAB is intended for formatted reports and headings rather than random-access screen placement.

Purpose

Inserts spaces until output reaches a requested character column.

Syntax

PRINT TAB(N);"TEXT"

Parameters and Elements

ElementDescription
NNumeric expression representing the target column.

Detailed Description

TAB only moves forward. If output has already passed the requested column, no backward cursor movement occurs. TAB is evaluated during PRINT processing and is most useful for headings and reports.

Programming Guidance

  • Use modest column values that fit the visible width.
  • Use PRINT @ when a row and column position must be specified independently.

Common Errors and Limitations

  • Negative or nonsensical targets are effectively limited by the generated spacing behavior.

Related Entries

Examples

The original runnable examples are retained below.

PRINT TAB(20);"CENTER AREA"
Contents20 / 136
TRS-80 MODEL 4 BASICPAGE 21

PRINT @ Position

PRINT @ places text at a simulated screen-memory position on a 64-column by 16-row display. Position zero is the upper-left character. The row is position divided by 64; the column is the remainder. Positions wrap within the 1024-character screen area. This feature is well suited to menus, scoreboards, and character animation.

Purpose

Writes text at a specific location in the simulated 64-by-16 character screen memory.

Syntax

PRINT @ position,"TEXT"PRINT @ expression;value

Parameters and Elements

ElementDescription
positionNumeric expression from 0 through 1023; values are wrapped into the screen area.
rowComputed as INT(position/64).
columnComputed as position MOD 64.

Detailed Description

PRINT @ allows menus, scoreboards, and animation without producing a scrolling line for every update. Text overwrites existing characters beginning at the selected position.

Programming Guidance

  • Calculate positions as row*64+column.
  • Erase a moving object by printing spaces at its previous position.

Common Errors and Limitations

  • Very long text can extend beyond the intended row in the emulator's line representation.
  • PRINT @ is an emulator screen feature, not a general browser pixel-graphics command.

Related Entries

Examples

The original runnable examples are retained below.

10 CLS
20 PRINT @ 0,"TOP LEFT"
30 PRINT @ 128,"ROW 2"
Contents21 / 136
TRS-80 MODEL 4 BASICPAGE 22

INPUT

INPUT pauses the program, displays a question prompt, and waits for a value. INPUT A stores a numeric value; INPUT A$ stores text. Press Enter to submit. BREAK, Esc, or Ctrl+C cancels a waiting INPUT and interrupts the program. Numeric input that cannot be parsed becomes zero in this emulator.

Purpose

Pauses a program and obtains a numeric or string value from the user.

Syntax

INPUT AINPUT A$

Parameters and Elements

ElementDescription
ASingle-letter numeric variable.
A$Single-letter string variable.

Detailed Description

INPUT displays a question prompt and waits for Enter. Numeric input is converted with browser number parsing; invalid numeric text becomes zero in this implementation. BREAK, Esc, or Ctrl+C cancels the wait and interrupts the program.

Programming Guidance

  • Print a descriptive prompt immediately before INPUT.
  • Validate ranges after numeric input and branch back when necessary.

Common Errors and Limitations

  • This version accepts one scalar variable per INPUT statement.
  • Array elements and comma-separated input lists are not documented as supported.

Related Entries

Examples

The original runnable examples are retained below.

10 INPUT A
20 PRINT "YOU ENTERED ";A
Contents22 / 136
TRS-80 MODEL 4 BASICPAGE 23

LET and Assignment

LET assigns a value to a variable or array element. LET is optional. Numeric expressions are stored in numeric variables; string expressions are stored in names ending with a dollar sign. Array elements must have been dimensioned before assignment.

Purpose

Stores the result of an expression in a scalar variable or array element.

Syntax

LET A=expressionA=expressionA$="text"X(I)=expressionN$(I)=string-expression

Parameters and Elements

ElementDescription
LETOptional keyword retained for traditional BASIC readability.
destinationNumeric variable, string variable, numeric array element, or string array element.
expressionValue evaluated before storage.

Detailed Description

The destination type determines whether the expression is interpreted as numeric or string. Array elements require a preceding DIM declaration. String assignments are limited to the emulator's configured maximum length.

Programming Guidance

  • Use LET in instructional listings when it makes assignment clearer.
  • Do not confuse equality testing inside IF with assignment at the beginning of a statement.

Common Errors and Limitations

  • Using an array before DIM, using the wrong number of subscripts, or exceeding a bound produces an array error.

Related Entries

Examples

The original runnable examples are retained below.

LET A=10
B=A*2
LET X(I)=B
N$="TRS-80"
Contents23 / 136
TRS-80 MODEL 4 BASICPAGE 24

REM Comments

REM marks a comment. The interpreter ignores the remainder of that statement. Comments should explain purpose, assumptions, data formats, and non-obvious calculations. Clear comments are especially valuable in programs that use many GOTO targets.

Purpose

Adds explanatory text to a program without executing it.

Syntax

REM comment text100 REM INITIALIZE ARRAYS

Detailed Description

The interpreter ignores the remainder of the REM statement. Comments can identify sections, explain formulas, describe variable use, or record compatibility changes made to an imported historical listing.

Programming Guidance

  • Explain why code exists rather than merely repeating what the statement visibly does.
  • Use line-numbered comments as section headings in long listings.

Related Entries

Examples

The original runnable examples are retained below.

10 REM INITIALIZE SCREEN
20 CLS
Contents24 / 136
TRS-80 MODEL 4 BASICPAGE 25

END

END terminates program execution normally. It is optional at the physical end of a program, but including it makes the intended stopping point clear and prevents accidental entry into subroutines placed later in the listing.

Purpose

Terminates program execution normally.

Syntax

END

Detailed Description

END prevents execution from continuing into later lines, especially subroutines placed after the main program. Reaching the physical end of the listing also stops execution, but an explicit END documents intent.

Programming Guidance

  • Place END before a block of subroutines when the main path must not fall through into them.

Related Entries

Examples

The original runnable examples are retained below.

100 END
500 REM SUBROUTINES MAY FOLLOW
Contents25 / 136
TRS-80 MODEL 4 BASICPAGE 26

Multiple Statements with Colon

A colon separates multiple statements on one numbered line. Colons inside quoted strings are not separators. Compact lines save listing space, but excessive chaining makes programs harder to debug. GOTO and loop behavior operate on the flattened statement sequence.

Purpose

Places more than one BASIC statement on the same numbered line.

Syntax

10 A=1:B=2:PRINT A+B

Detailed Description

The interpreter divides a line at top-level colons while preserving colons inside quoted strings. Statements then execute in their written order. Branches operate on the flattened statement sequence.

Programming Guidance

  • Use colons sparingly; one statement per line is easier to debug and document.
  • Do not assume a GOTO target can enter the middle of a multi-statement line; targets select the line's first statement.

Common Errors and Limitations

  • A colon inside an unterminated string may be parsed incorrectly because the quotation itself is invalid.

Related Entries

Examples

The original runnable examples are retained below.

10 A=1: B=2: PRINT A+B
Contents26 / 136
TRS-80 MODEL 4 BASICPAGE 27

GOTO

GOTO transfers execution to the first statement on the specified line. The target line must exist. Unstructured jumps are historically common in BASIC, but reserve line-number ranges for major sections and document important targets.

Purpose

Transfers execution unconditionally to a numbered program line.

Syntax

GOTO line-number

Parameters and Elements

ElementDescription
line-numberExisting numbered line that becomes the next execution point.

Detailed Description

GOTO is useful for main loops, retries, state transitions, and exits from conditional sections. The emulator jumps to the first statement on the target line.

Programming Guidance

  • Reserve line-number ranges for major program sections.
  • Use GOSUB for reusable routines that must return.
  • Use BREAK to recover from an accidental endless GOTO loop.

Common Errors and Limitations

  • A nonexistent target produces NO SUCH LINE.
  • Excessive unstructured jumps make maintenance difficult.

Related Entries

Examples

The original runnable examples are retained below.

10 PRINT "AGAIN"
20 GOTO 10
Contents27 / 136
TRS-80 MODEL 4 BASICPAGE 28

IF...THEN

IF evaluates a numeric condition. Zero is false; any nonzero value is true. In this emulator, THEN is followed by a line number. When true, execution jumps to that line. When false, execution continues with the next statement.

Purpose

Tests a condition and branches to a line number when the condition is true.

Syntax

IF condition THEN line-number

Parameters and Elements

ElementDescription
conditionNumeric expression; zero is false and any nonzero value is true.
line-numberTarget executed only when the condition is true.

Detailed Description

Comparisons return numeric 1 or 0 and can be combined with AND, OR, and NOT. When the condition is false, execution continues with the next statement.

Programming Guidance

  • Use parentheses in compound conditions.
  • Design the fall-through path to be easy to understand.

Common Errors and Limitations

  • This emulator documents THEN followed by a line number, not an arbitrary inline statement.

Related Entries

Examples

The original runnable examples are retained below.

10 IF A>5 THEN 100
20 PRINT "A IS 5 OR LESS"
Contents28 / 136
TRS-80 MODEL 4 BASICPAGE 29

Comparison Operators

Comparisons return 1 for true and 0 for false. Supported operators are =, <>, <, <=, >, and >=. Comparisons may be combined with AND, OR, and NOT. Parentheses make intent clear and reduce precedence mistakes.

Purpose

Compares numeric values and returns 1 for true or 0 for false.

Syntax

A=BA<>BAA<=BA>BA>=B

Parameters and Elements

ElementDescription
=Equal
<>Not equal
<Less than
<=Less than or equal
>Greater than
>=Greater than or equal

Detailed Description

Comparison results are ordinary numeric values. They may be printed, assigned, or used as IF conditions. Floating-point calculations can contain tiny rounding differences, so exact equality after complex decimal arithmetic should be used carefully.

Programming Guidance

  • Use a tolerance test such as ABS(A-B)<0.0001 for approximate decimal equality.
  • Parenthesize comparisons before combining them with AND or OR.

Related Entries

Examples

The original runnable examples are retained below.

PRINT 5=5
PRINT 5<>4
PRINT (A>=1) AND (A<=10)
Contents29 / 136
TRS-80 MODEL 4 BASICPAGE 30

GOSUB and RETURN

GOSUB transfers control to a subroutine and stores the return point. RETURN resumes after the calling GOSUB. Subroutines are useful for repeated printing, calculations, input validation, and screen setup. RETURN without a matching GOSUB causes an error.

Purpose

Calls a reusable subroutine and later resumes execution after the call.

Syntax

GOSUB line-numberRETURN

Parameters and Elements

ElementDescription
line-numberFirst line of the subroutine.
RETURNUses the most recently saved return point.

Detailed Description

GOSUB pushes the current execution position onto a stack and branches. RETURN pops that position and continues after the GOSUB. Nested subroutine calls are permitted as stack space allows.

Programming Guidance

  • Place subroutines after END and give each a REM heading.
  • Ensure every normal subroutine path reaches RETURN.

Common Errors and Limitations

  • RETURN WITHOUT GOSUB occurs when the return stack is empty.
  • A GOSUB target that does not exist produces NO SUCH LINE.

Related Entries

Examples

The original runnable examples are retained below.

10 GOSUB 100
20 END
100 PRINT "SUBROUTINE"
110 RETURN
Contents30 / 136
TRS-80 MODEL 4 BASICPAGE 31

FOR...NEXT

FOR initializes a single-letter numeric variable, records an ending value and step, and begins a loop. NEXT increments the variable and either repeats or exits. The default step is 1. Negative steps count downward. The NEXT variable must match the active FOR frame.

Purpose

Repeats a block of statements while advancing a numeric control variable.

Syntax

FOR I=start TO finishFOR I=start TO finish STEP incrementNEXT I

Parameters and Elements

ElementDescription
ISingle-letter numeric loop variable.
startInitial numeric value.
finishInclusive ending value.
incrementAmount added each repetition; defaults to 1.

Detailed Description

FOR assigns the start value and records the loop frame. NEXT increments the variable and repeats when it has not passed the ending value. Positive and negative steps are supported.

Programming Guidance

  • Do not modify the loop variable inside the loop unless the altered control behavior is intentional.
  • Use different variables for nested loops.

Common Errors and Limitations

  • NEXT WITHOUT FOR and NEXT VARIABLE MISMATCH indicate a damaged loop structure.
  • A zero STEP can create an endless loop; use BREAK to stop it.

Related Entries

Examples

The original runnable examples are retained below.

10 FOR I=1 TO 10
20 PRINT I
30 NEXT I
Contents31 / 136
TRS-80 MODEL 4 BASICPAGE 32

STEP

STEP changes the increment used by FOR. Fractional and negative steps are accepted. A positive step continues while the variable is less than or equal to the ending value. A negative step continues while it is greater than or equal to the ending value.

Purpose

Specifies the amount and direction by which a FOR loop variable changes.

Syntax

FOR I=1 TO 10 STEP 2FOR I=10 TO 1 STEP -1

Detailed Description

Positive STEP values count upward; negative values count downward. The finish value remains inclusive. Fractional steps are accepted because variables use floating-point numbers.

Programming Guidance

  • Choose a step sign that moves toward the ending value.
  • Avoid relying on exact equality after many fractional increments.

Common Errors and Limitations

  • A step of zero never moves toward completion and can create an infinite loop.

Related Entries

Examples

The original runnable examples are retained below.

FOR I=10 TO 0 STEP -2
PRINT I
NEXT I
Contents32 / 136
TRS-80 MODEL 4 BASICPAGE 33

Nested Loops

Loops may be nested. Each NEXT must close the most recent matching FOR. Nested loops are useful for tables, grids, array initialization, and cellular automata. Keep loop variables distinct and indent the source in an external editor when possible.

Purpose

Uses one FOR/NEXT loop inside another to process rows, columns, combinations, or multidimensional arrays.

Syntax

FOR R=0 TO 5 FOR C=0 TO 5 A(R,C)=R*C NEXT CNEXT R

Detailed Description

The innermost active loop completes for each iteration of the outer loop. The emulator tracks loop frames in stack order, so NEXT must match the active structure.

Programming Guidance

  • Use R and C for row and column where that improves readability.
  • Keep NEXT statements visually aligned in files edited outside the emulator.

Common Errors and Limitations

  • Crossing loop structures or closing them in the wrong order produces mismatch errors.

Related Entries

Examples

The original runnable examples are retained below.

10 FOR R=1 TO 5
20 FOR C=1 TO 10
30 PRINT "*";
40 NEXT C
50 PRINT
60 NEXT R
Contents33 / 136
TRS-80 MODEL 4 BASICPAGE 34

PAUSE

PAUSE milliseconds delays execution for approximately the requested number of milliseconds. Unlike a busy-wait BASIC loop, PAUSE yields to the browser and remains interruptible. Use PAUSE for animation pacing and demonstrations. Browser timing is not suitable for precision measurement.

Purpose

Delays program execution for approximately a specified number of milliseconds while keeping the browser responsive.

Syntax

PAUSE milliseconds

Parameters and Elements

ElementDescription
millisecondsNumeric expression converted to a nonnegative integer delay.

Detailed Description

PAUSE uses asynchronous browser timing rather than a busy loop. The interpreter continues checking for BREAK during the delay, making it suitable for animation and demonstrations.

Programming Guidance

  • Use PAUSE 50 to PAUSE 500 for visible animation, depending on the effect.
  • Do not use PAUSE as a precision timer.

Common Errors and Limitations

  • Browser scheduling, background tabs, and power-saving modes can make the actual delay longer.

Related Entries

Examples

The original runnable examples are retained below.

10 PRINT "TICK"
20 PAUSE 500
30 GOTO 10
Contents34 / 136
TRS-80 MODEL 4 BASICPAGE 35

DATA

DATA stores constant values inside the program. Items are separated by commas and may be numeric or quoted strings. DATA statements do nothing when reached during normal execution; they are scanned before RUN to construct the data pool.

Purpose

Stores constant numeric and string values inside the program for sequential retrieval by READ.

Syntax

DATA 10,20,30DATA "RED","GREEN","BLUE"

Detailed Description

DATA statements are scanned before RUN and placed into a shared data pool. Reaching a DATA line during ordinary execution performs no visible action.

Programming Guidance

  • Keep related data together and document its field order with REM.
  • Use quoted strings when commas or spaces belong to the data text.

Common Errors and Limitations

  • Expressions that depend on changing runtime variables should not be treated as portable DATA constants.

Related Entries

Examples

The original runnable examples are retained below.

10 DATA 10,20,30,"DONE"
Contents35 / 136
TRS-80 MODEL 4 BASICPAGE 36

READ

READ obtains the next item from the DATA pool and places it into a numeric or string variable. READ past the final item causes an error. This emulator currently documents READ into scalar variables; use assignment afterward to place values into arrays.

Purpose

Retrieves the next value from the program's DATA pool.

Syntax

READ AREAD A$

Parameters and Elements

ElementDescription
ANumeric scalar destination.
A$String scalar destination.

Detailed Description

Each READ advances the shared DATA pointer. Values are converted to the destination type. To place a value into an array, READ it into a scalar and then assign the scalar to the array element.

Programming Guidance

  • Match the number and type order of READ statements to DATA items.
  • Use loops when reading repeated records.

Common Errors and Limitations

  • READ PAST END OF DATA occurs after the last available item.

Related Entries

Examples

The original runnable examples are retained below.

10 DATA 5,10,15
20 READ A
30 PRINT A
Contents36 / 136
TRS-80 MODEL 4 BASICPAGE 37

RESTORE

RESTORE resets the DATA pointer to the first DATA item. It permits the same data list to be read again. This implementation restores to the beginning rather than to a particular line number.

Purpose

Moves the DATA pointer back to the first DATA item.

Syntax

RESTORE

Detailed Description

After RESTORE, the next READ returns the first data value again. This implementation does not document RESTORE with a line-number argument.

Programming Guidance

  • Use RESTORE when the same lookup data must be processed more than once.

Related Entries

Examples

The original runnable examples are retained below.

10 DATA 1,2
20 READ A
30 RESTORE
40 READ B
Contents37 / 136
TRS-80 MODEL 4 BASICPAGE 38

Numeric Variables

Numeric variable names are the single letters A through Z. Values use JavaScript floating-point numbers internally. Integer-looking results are displayed as integers; other results are rounded for readable output. Programs that require exact decimal financial arithmetic should account for binary floating-point behavior.

Purpose

Stores numeric values used in calculations, loops, comparisons, and array subscripts.

Syntax

A=10R=PI/2PRINT A

Detailed Description

Scalar numeric names are A through Z. Values are JavaScript double-precision floating-point numbers internally. This offers a large range but includes the usual binary floating-point rounding behavior.

Programming Guidance

  • Choose mnemonic single letters where possible, such as I for index, R for row or radius, and C for count or column.
  • Use INT or ROUND when an integer result is required.

Common Errors and Limitations

  • A single letter can hold only one scalar value at a time; use DIM when many related values are needed.

Related Entries

Examples

The original runnable examples are retained below.

Contents38 / 136
TRS-80 MODEL 4 BASICPAGE 39

String Variables

String variable names are A$ through Z$. Strings can be assigned from literals, string variables, string functions, or concatenations. Stored strings are limited to 255 characters by assignment in this emulator.

Purpose

Stores text values for messages, names, menus, and input.

Syntax

A$="MODEL 4"PRINT A$

Detailed Description

Scalar string names are A$ through Z$. String expressions can combine literals, variables, and supported string functions. Assignment truncates strings to the emulator's configured maximum length.

Programming Guidance

  • Use the dollar sign consistently; A and A$ are different variables.
  • Use TRIM$, UPPER$, or LOWER$ to normalize user input.

Common Errors and Limitations

  • Numeric and string expressions are not interchangeable except through VAL and STR$.

Related Entries

Examples

The original runnable examples are retained below.

A$="MODEL "+"4"
PRINT A$
Contents39 / 136
TRS-80 MODEL 4 BASICPAGE 40

DIM Overview

DIM creates numeric or string arrays. Array names use a single letter, optionally followed by $. Dimensions are inclusive, so DIM X(68) permits subscripts 0 through 68. Arrays are reset when RUN begins or CLEAR is issued. DIM may contain expressions such as DIM X(M) if M has already been assigned.

Purpose

Declares numeric or string arrays and establishes their valid subscript ranges.

Syntax

DIM X(68)DIM X (M)DIM A(10,10)DIM N$(20)

Parameters and Elements

ElementDescription
array nameSingle letter, optionally followed by $ for strings.
dimensionInclusive upper bound; DIM X(68) creates elements X(0) through X(68).
multiple dimensionsComma-separated upper bounds for tables or grids.

Detailed Description

DIM must execute before an array is read or written. Dimension expressions are evaluated at runtime, so a variable such as M may determine the size if it has already been assigned. New elements initially read as zero or an empty string.

Programming Guidance

  • Dimension arrays near the beginning of the program.
  • Match loop limits exactly to declared bounds.
  • Use two arrays when a generation must be calculated without overwriting the current state.

Common Errors and Limitations

  • Negative dimensions, missing bounds, repeated incompatible declarations, or invalid syntax cause DIM errors.

Related Entries

Examples

The original runnable examples are retained below.

5 LET M=68
10 DIM X(M)
20 DIM Y(M)
Contents40 / 136
TRS-80 MODEL 4 BASICPAGE 41

One-Dimensional Arrays

A one-dimensional array is a numbered list of elements. Use it for scores, samples, character states, lookup tables, and histories. Every element initially contains zero, or an empty string for string arrays. Subscripts are truncated to integers.

Purpose

Stores an indexed sequence of related values under one array name.

Syntax

DIM X(100)X(I)=valuePRINT X(I)

Detailed Description

One-dimensional arrays model lists, time series, scores, counters, and cellular states. The lower bound is zero and the declared number is the inclusive upper bound.

Programming Guidance

  • Use FOR I=0 TO upper-bound to initialize every element.
  • Reserve boundary elements when an algorithm needs neighbor access.

Common Errors and Limitations

  • References outside 0 through the upper bound produce SUBSCRIPT OUT OF RANGE.

Related Entries

Examples

The original runnable examples are retained below.

10 DIM X(10)
20 FOR I=0 TO 10
30 X(I)=I*I
40 NEXT I
Contents41 / 136
TRS-80 MODEL 4 BASICPAGE 42

Multidimensional Arrays

Multiple dimensions create tables or higher-dimensional grids. DIM A(10,10) permits row and column subscripts from 0 through 10. The number of subscripts used later must match the declaration. Values are stored sparsely in the emulator, so untouched elements consume minimal entry storage.

Purpose

Stores table, matrix, grid, or higher-dimensional data addressed by more than one subscript.

Syntax

DIM A(10,10)A(R,C)=valuePRINT A(R,C)

Detailed Description

Each dimension has an inclusive zero-based range. The number of subscripts in every later reference must equal the number declared by DIM. The emulator stores values using a sparse key representation, so untouched elements remain at their default value.

Programming Guidance

  • Use nested loops to initialize or display grids.
  • Document which subscript represents rows, columns, layers, or other axes.

Common Errors and Limitations

  • Using too few or too many subscripts produces WRONG NUMBER OF SUBSCRIPTS.

Related Entries

Examples

The original runnable examples are retained below.

10 DIM A(5,5)
20 A(2,3)=99
30 PRINT A(2,3)
Contents42 / 136
TRS-80 MODEL 4 BASICPAGE 43

String Arrays

A string array is dimensioned with a dollar-sign name. Each unassigned element reads as an empty string. String arrays are useful for menus, names, messages, and text maps.

Purpose

Stores multiple text values that can be selected by a numeric subscript.

Syntax

DIM N$(20)N$(0)="FIRST"PRINT N$(I)

Detailed Description

String arrays are useful for menu labels, names, map rows, messages, and lookup tables. Unassigned elements return an empty string.

Programming Guidance

  • Keep index meanings documented, especially when zero has a special role.
  • Use LEN or TRIM$ when validating stored text.

Common Errors and Limitations

  • The array name must include $ both in DIM and in every reference.

Related Entries

Examples

The original runnable examples are retained below.

10 DIM N$(3)
20 N$(0)="ZERO"
30 PRINT N$(0)
Contents43 / 136
TRS-80 MODEL 4 BASICPAGE 44

Array Subscripts

Subscripts may be constants, variables, arithmetic expressions, or function results. They are evaluated when the element is read or written and truncated to integers. Negative subscripts and subscripts greater than the declared upper bound cause SUBSCRIPT OUT OF RANGE.

Purpose

Selects a particular element from an array.

Syntax

X(5)X(I)X(I+1)A(R,C)

Parameters and Elements

ElementDescription
subscript expressionNumeric expression evaluated and truncated to an integer.
valid rangeZero through the corresponding declared upper bound.

Detailed Description

Subscripts can contain variables, arithmetic, and supported numeric functions. They are checked every time an element is read or written.

Programming Guidance

  • Check both ends of neighbor loops; X(I-2) requires I to start at least at 2.
  • Print subscript values during debugging when an out-of-range error is unexpected.

Common Errors and Limitations

  • Negative values and values above the bound produce SUBSCRIPT OUT OF RANGE.

Related Entries

Examples

The original runnable examples are retained below.

X(I+1)=X(I)*2
PRINT A(R,C)
Contents44 / 136
TRS-80 MODEL 4 BASICPAGE 45

Array Errors

ARRAY NOT DIMENSIONED means an element was used before DIM. WRONG NUMBER OF SUBSCRIPTS means the reference does not match the declared rank. SUBSCRIPT OUT OF RANGE means an index is below zero or above its upper bound. NEGATIVE ARRAY DIMENSION and BAD DIM STATEMENT report invalid declarations.

Purpose

Explains runtime failures caused by invalid declarations or references.

Syntax

ARRAY NOT DIMENSIONEDWRONG NUMBER OF SUBSCRIPTSSUBSCRIPT OUT OF RANGEBAD DIM STATEMENT

Detailed Description

Array checking protects the program from silently reading or writing an unintended element. The error usually identifies a missing DIM, an incorrect loop limit, a neighbor calculation at an edge, or a mismatch between one- and two-dimensional use.

Programming Guidance

  • Verify DIM executes before the failing line.
  • Print the current subscript and declared limit.
  • Examine loops using TO M versus TO M-1.

Related Entries

Examples

The original runnable examples are retained below.

Contents45 / 136
TRS-80 MODEL 4 BASICPAGE 46

Arithmetic Operators

The arithmetic operators are +, -, *, /, ^, MOD, and postfix factorial !. Parentheses control evaluation order. Division or modulus by zero causes an error. Exponentiation uses JavaScript Math.pow behavior.

Purpose

Performs numeric calculations.

Syntax

A+BA-BA*BA/BA^BA MOD BN!

Parameters and Elements

ElementDescription
+Addition
-Subtraction or unary negation
*Multiplication
/Division
^Exponentiation
MODRemainder
!Postfix factorial

Detailed Description

Arithmetic expressions may contain constants, variables, array elements, functions, and parentheses. Normal precedence applies, but parentheses are strongly recommended in mixed expressions.

Programming Guidance

  • Use MOD for periodic behavior and divisibility tests.
  • Use ^ for powers and SQR for square roots.
  • Use factorial only for nonnegative integer-sized values.

Common Errors and Limitations

  • Division or MOD by zero produces a runtime error.
  • Large powers may overflow to browser infinity.

Related Entries

Examples

The original runnable examples are retained below.

PRINT (2+3)*4
PRINT 2^8
PRINT 10 MOD 3
PRINT 5!
Contents46 / 136
TRS-80 MODEL 4 BASICPAGE 47

Logical Operators

AND is true when both operands are nonzero. OR is true when either operand is nonzero. NOT converts zero to 1 and nonzero to 0. Logical results are numeric and can be printed, assigned, or used in IF.

Purpose

Combines or reverses truth values represented numerically.

Syntax

condition1 AND condition2condition1 OR condition2NOT condition

Parameters and Elements

ElementDescription
ANDReturns 1 only when both operands are nonzero.
ORReturns 1 when either operand is nonzero.
NOTReturns 1 for zero and 0 for nonzero.

Detailed Description

Logical operations are most commonly used inside IF, but their numeric results can also be assigned or printed.

Programming Guidance

  • Parenthesize each comparison before combining it.
  • Remember that any nonzero value counts as true.

Related Entries

Examples

The original runnable examples are retained below.

PRINT (A>0) AND (A<10)
PRINT NOT 0
Contents47 / 136
TRS-80 MODEL 4 BASICPAGE 48

ABS, INT, FIX, ROUND, SGN

ABS returns magnitude. INT rounds downward. FIX truncates toward zero. ROUND returns the nearest integer using JavaScript rounding behavior. SGN returns -1, 0, or 1. These functions are helpful for numeric formatting, loop bounds, and simulations.

Purpose

Provides common value-normalization and integer-conversion operations.

Syntax

ABS(X)INT(X)FIX(X)ROUND(X)SGN(X)

Parameters and Elements

ElementDescription
ABSMagnitude without sign.
INTGreatest integer less than or equal to X.
FIXTruncates toward zero.
ROUNDRounds to the nearest integer using browser behavior.
SGNReturns -1, 0, or 1.

Detailed Description

INT and FIX differ for negative values: INT(-3.1) is -4, while FIX(-3.1) is -3. SGN is useful for direction and comparison logic.

Programming Guidance

  • Use ABS(A-B) for tolerance comparisons.
  • Use INT(RND()*N) carefully; RANDINT is clearer for inclusive integer ranges.

Related Entries

Examples

The original runnable examples are retained below.

PRINT ABS(-25)
PRINT INT(-3.1)
PRINT FIX(-3.9)
PRINT SGN(-8)
Contents48 / 136
TRS-80 MODEL 4 BASICPAGE 49

SQR, EXP, LOG

SQR returns the square root and rejects negative input. EXP raises e to a power. LOG returns the natural logarithm. Very large or invalid mathematical results follow browser numeric behavior where not explicitly trapped.

Purpose

Calculates square roots, exponential values, and natural logarithms.

Syntax

SQR(X)EXP(X)LOG(X)

Parameters and Elements

ElementDescription
SQR(X)Square root; X must be nonnegative.
EXP(X)e raised to X.
LOG(X)Natural logarithm; mathematically requires X greater than zero.

Detailed Description

These functions use the browser's standard mathematical library. They are useful in geometry, growth and decay, statistics, and scientific calculations.

Programming Guidance

  • Check domains before calling SQR or LOG.
  • Use LOG(X)/LOG(10) when a base-10 logarithm is needed.

Common Errors and Limitations

  • SQR of a negative value is explicitly rejected.
  • Invalid logarithm inputs may produce a non-finite browser numeric result.

Related Entries

Examples

The original runnable examples are retained below.

PRINT SQR(144)
PRINT EXP(1)
PRINT LOG(E)
Contents49 / 136
TRS-80 MODEL 4 BASICPAGE 50

SIN, COS, TAN

Trigonometric functions use radians. Convert degrees to radians by multiplying by PI/180. TAN becomes very large near odd multiples of PI/2 because of floating-point approximation.

Purpose

Evaluates the principal trigonometric functions using radians.

Syntax

SIN(X)COS(X)TAN(X)

Parameters and Elements

ElementDescription
XAngle measured in radians.

Detailed Description

Convert degrees with radians=degrees*PI/180. These functions support geometry, oscillation, circular movement, and waveform calculations.

Programming Guidance

  • Store the converted angle in a variable when several trig functions use it.
  • Expect rounding near values that are mathematically zero.

Common Errors and Limitations

  • TAN grows extremely large near odd multiples of PI/2.

Related Entries

Examples

The original runnable examples are retained below.

R=45*PI/180
PRINT SIN(R),COS(R),TAN(R)
Contents50 / 136
TRS-80 MODEL 4 BASICPAGE 51

ASN, ACS, ATN

Inverse trigonometric functions return radians. ASN and ACS expect values in the mathematical domain -1 through 1. ATN accepts any finite numeric value.

Purpose

Returns inverse trigonometric angles in radians.

Syntax

ASN(X)ACS(X)ATN(X)

Parameters and Elements

ElementDescription
ASNArcsine; X normally lies from -1 to 1.
ACSArccosine; X normally lies from -1 to 1.
ATNArctangent; accepts any finite X.

Detailed Description

Multiply the returned radians by 180/PI to obtain degrees. Inverse functions are useful when deriving an angle from a ratio or coordinate relationship.

Programming Guidance

  • Clamp computed ASN or ACS inputs to -1 through 1 when floating-point rounding may exceed the domain slightly.

Related Entries

Examples

The original runnable examples are retained below.

PRINT ATN(1)*180/PI
Contents51 / 136
TRS-80 MODEL 4 BASICPAGE 52

MIN and MAX

MIN and MAX accept multiple comma-separated numeric expressions. They return the smallest or largest result. Use them to clamp ranges, analyze data, or compare candidates.

Purpose

Selects the smallest or largest value from a list of numeric expressions.

Syntax

MIN(A,B,...)MAX(A,B,...)

Detailed Description

Every argument is evaluated before the result is selected. These functions are useful for limits, range analysis, clipping, and comparisons among several candidates.

Programming Guidance

  • Use MAX(lower,MIN(value,upper)) to clamp a value into a range.

Common Errors and Limitations

  • Provide at least one valid numeric argument.

Related Entries

Examples

The original runnable examples are retained below.

PRINT MIN(10,20,5)
PRINT MAX(10,20,5)
Contents52 / 136
TRS-80 MODEL 4 BASICPAGE 53

Factorial

The postfix ! operator and FACT(X) calculate factorial after truncating X to an integer. Negative values are rejected. Values above 170 are rejected because they exceed useful finite JavaScript number range.

Purpose

Calculates the product of all positive integers from 1 through a nonnegative integer.

Syntax

N!FACT(N)

Detailed Description

The argument is truncated to an integer. Both syntaxes use the same implementation. Factorials are used in combinations, permutations, probability, and series expansions.

Programming Guidance

  • Use small values; factorial grows extremely rapidly.
  • 0! and 1! both equal 1.

Common Errors and Limitations

  • Negative values produce NEGATIVE FACTORIAL.
  • Values above 170 produce FACTORIAL TOO LARGE.

Related Entries

Examples

The original runnable examples are retained below.

PRINT 6!
PRINT FACT(6)
Contents53 / 136
TRS-80 MODEL 4 BASICPAGE 54

RND and RANDINT

RND or RND() returns a pseudo-random value from zero up to but not including one. RND(X) returns that value multiplied by X. RANDINT(A,B) returns an integer from A through B inclusive. Random sequences are supplied by the browser and are not cryptographically secure.

Purpose

Generates pseudo-random values for games, simulations, sampling, and randomized initialization.

Syntax

RNDRND()RND(X)RANDINT(A,B)

Parameters and Elements

ElementDescription
RND / RND()Value from 0 inclusive to 1 exclusive.
RND(X)Random fraction multiplied by X.
RANDINT(A,B)Integer from A through B inclusive.

Detailed Description

The emulator uses the browser's pseudo-random generator. RND(1) therefore behaves like RND()*1, which is useful for compatibility with listings that include a dummy argument.

Programming Guidance

  • Use RANDINT(1,6) for a die.
  • Use IF RND()<0.5 THEN line for a roughly even choice.
  • Do not use these functions for passwords, encryption, or security.

Related Entries

Examples

The original runnable examples are retained below.

R=RND(1)*10
D=RANDINT(1,6)
Contents54 / 136
TRS-80 MODEL 4 BASICPAGE 55

PI, E, TRUE, FALSE

PI and E provide common mathematical constants. TRUE equals 1 and FALSE equals 0. These names can be used wherever a numeric expression is accepted.

Purpose

Provides named numeric constants.

Syntax

PIETRUEFALSE

Parameters and Elements

ElementDescription
PIApproximately 3.141592653589793.
EApproximately 2.718281828459045.
TRUENumeric 1.
FALSENumeric 0.

Detailed Description

Named constants make mathematical and logical expressions clearer than embedding approximate decimal values.

Programming Guidance

  • Convert degrees using degrees*PI/180.
  • Use TRUE and FALSE when they improve readability, remembering that BASIC conditions accept any nonzero value as true.

Related Entries

Examples

The original runnable examples are retained below.

Contents55 / 136
TRS-80 MODEL 4 BASICPAGE 56

LEN, ASC, VAL

LEN returns string length. ASC returns the character code of the first character, or zero for an empty string. VAL converts the beginning of a numeric-looking string to a number; invalid text becomes zero.

Purpose

Inspects or converts string data.

Syntax

LEN(A$)ASC(A$)VAL(A$)

Parameters and Elements

ElementDescription
LENNumber of characters.
ASCCharacter code of the first character; zero for an empty string.
VALNumeric conversion of text; invalid text becomes zero.

Detailed Description

These functions help validate input, decode characters, and convert text fields into numbers.

Programming Guidance

  • Use TRIM$ before VAL when input may contain surrounding spaces.
  • Check LEN before relying on ASC of user input.

Related Entries

Examples

The original runnable examples are retained below.

PRINT LEN("MODEL 4")
PRINT ASC("A")
PRINT VAL("123")+7
Contents56 / 136
TRS-80 MODEL 4 BASICPAGE 57

CHR$ and STR$

CHR$(N) returns the character whose 8-bit code is N. STR$(N) converts a numeric value to text. These functions bridge numeric and string processing.

Purpose

Converts between character codes, numbers, and strings.

Syntax

CHR$(N)STR$(N)

Parameters and Elements

ElementDescription
CHR$(N)Character corresponding to the low 8 bits of N.
STR$(N)Text representation of a numeric expression.

Detailed Description

CHR$ is useful for generated characters and simple text protocols. STR$ allows numeric results to participate in string concatenation.

Programming Guidance

  • Use ASC to reverse a CHR$ conversion for ordinary characters.
  • Be aware that browser character behavior is Unicode-based even though CHR$ masks to an 8-bit value.

Related Entries

Examples

The original runnable examples are retained below.

PRINT CHR$(65)
A$=STR$(123)
Contents57 / 136
TRS-80 MODEL 4 BASICPAGE 58

LEFT$, RIGHT$, MID$

LEFT$ returns characters from the beginning, RIGHT$ from the end, and MID$ from a one-based starting position. MID$ may include an optional length. Out-of-range slicing follows safe browser string behavior and returns available text.

Purpose

Extracts a substring from the beginning, end, or middle of a string.

Syntax

LEFT$(A$,N)RIGHT$(A$,N)MID$(A$,START)MID$(A$,START,LENGTH)

Parameters and Elements

ElementDescription
A$Source string expression.
N / LENGTHNumber of characters.
STARTOne-based starting position.

Detailed Description

LEFT$ and RIGHT$ select from the ends. MID$ subtracts one from START to map traditional BASIC indexing to browser string indexing. Requests beyond available text return the portion that exists.

Programming Guidance

  • Use LEN to determine safe positions.
  • Use MID$ in loops to examine one character at a time.

Related Entries

Examples

The original runnable examples are retained below.

A$="RADIO SHACK"
PRINT LEFT$(A$,5)
PRINT RIGHT$(A$,5)
PRINT MID$(A$,7,5)
Contents58 / 136
TRS-80 MODEL 4 BASICPAGE 59

UPPER$, LOWER$, TRIM$

UPPER$ and LOWER$ change letter case. TRIM$ removes leading and trailing whitespace. They are emulator conveniences useful when comparing input and preparing reports.

Purpose

Normalizes the case and surrounding whitespace of strings.

Syntax

UPPER$(A$)LOWER$(A$)TRIM$(A$)

Detailed Description

These emulator extensions simplify menu input and text processing. UPPER$ and LOWER$ change letter case; TRIM$ removes whitespace at both ends.

Programming Guidance

  • Normalize user input before comparing it with a command word.
  • TRIM$ does not remove spaces inside the string.

Related Entries

Examples

The original runnable examples are retained below.

Contents59 / 136
TRS-80 MODEL 4 BASICPAGE 60

INKEY$

INKEY$ returns the last ordinary key pressed and then clears the stored key. It does not wait. Programs can poll INKEY$ in a loop for simple interactive control, but should include PAUSE or other pacing to avoid excessive CPU use.

Purpose

Returns the most recently pressed ordinary key without pausing the program.

Syntax

A$=INKEY$

Detailed Description

INKEY$ is nonblocking. After it returns the stored key, the stored value is cleared, so a later call returns an empty string until another key is pressed.

Programming Guidance

  • Poll INKEY$ inside a paced loop.
  • Use PAUSE to avoid consuming unnecessary CPU while waiting.

Common Errors and Limitations

  • Special browser shortcuts and modifier combinations may not appear as ordinary INKEY$ characters.

Related Entries

Examples

The original runnable examples are retained below.

10 A$=INKEY$
20 IF A$="" THEN 10
30 PRINT A$
Contents60 / 136
TRS-80 MODEL 4 BASICPAGE 61

Operator Precedence

Use parentheses whenever an expression mixes arithmetic, comparison, and logical operations. The evaluator handles unary signs, exponentiation, multiplication and division, addition and subtraction, comparisons, NOT, AND, and OR. Parentheses are the clearest way to communicate intended order.

Purpose

Determines the order in which parts of a mixed expression are evaluated.

Syntax

(parentheses)unary sign / NOT^ and !* / MOD+-comparisonsANDOR

Detailed Description

The parser implements precedence rules, but complex expressions are easier to read and safer to port when parentheses explicitly state the desired order.

Programming Guidance

  • Write (A>0) AND (A<10), not A>0 AND A<10.
  • Break very long formulas into intermediate variables.

Common Errors and Limitations

  • Do not rely on precedence that belongs to another BASIC dialect without testing it in this emulator.

Related Entries

Examples

The original runnable examples are retained below.

Contents61 / 136
TRS-80 MODEL 4 BASICPAGE 62

Screen Geometry

The simulated character display is modeled as 64 columns by 16 rows for PRINT @ addressing. Normal terminal output can scroll beyond those dimensions. PRINT @ updates the screen-memory region and keeps it visible near the top.

Contents62 / 136
TRS-80 MODEL 4 BASICPAGE 63

Character Graphics

Text characters can act as graphics. Asterisks, spaces, plus signs, slashes, and letters can form charts, mazes, vehicles, or cellular automata. PRINT @ is useful for placing individual objects, while semicolon PRINT is useful for building rows.

Contents63 / 136
TRS-80 MODEL 4 BASICPAGE 64

Animation

Animation usually follows four steps: erase or clear the previous image, update state variables, draw the new image, and PAUSE. Use BREAK to stop an animation. Avoid extremely short GOTO loops without pacing, because they can flood the terminal with output.

Contents64 / 136
TRS-80 MODEL 4 BASICPAGE 65

Debugging with PRINT

Temporary PRINT statements reveal variable values, branch choices, and array contents. Include labels so the output is meaningful. Remove or comment debug lines after the program works.

PRINT "I=";I;" C=";C;" X(I)=";X(I)
Contents65 / 136
TRS-80 MODEL 4 BASICPAGE 66

Debugging GOTO Programs

Create a line-number map before writing a large program. Typical ranges might reserve 10-99 for initialization, 100-499 for the main loop, 500-799 for subroutines, and 800-999 for error handling. LIST verifies that every target exists.

Contents66 / 136
TRS-80 MODEL 4 BASICPAGE 67

Debugging Arrays

Check DIM upper bounds, loop start and end values, and every calculated subscript. Remember that DIM X(68) includes both X(0) and X(68). A loop from 0 TO M is therefore valid when the array was dimensioned with M.

Contents67 / 136
TRS-80 MODEL 4 BASICPAGE 68

Avoiding Infinite Loops

Every intentional loop should have an exit condition or be designed to run until BREAK. During development, add a counter or PAUSE. The new interrupt system lets you recover from GOTO loops, long FOR loops, pauses, and waiting input without reloading the page.

Contents68 / 136
TRS-80 MODEL 4 BASICPAGE 69

Program Structure

Begin with initialization, then enter a main loop, then place subroutines after END. Use comments and consistent line-number ranges. Keep calculations in small sections and avoid changing a FOR control variable inside its loop unless the effect is deliberate.

Contents69 / 136
TRS-80 MODEL 4 BASICPAGE 70

Performance and Browser Pacing

The interpreter periodically yields to the browser so the screen remains responsive and BREAK can be detected. A JavaScript implementation does not execute at the same speed as a physical 1980s computer. Timing loops therefore should not be used as clocks; use PAUSE for visible pacing.

Contents70 / 136
TRS-80 MODEL 4 BASICPAGE 71

Compatibility Notes

This is a TinyBASIC-style web interpreter inspired by the TRS-80 Model 4. It is not a byte-for-byte Microsoft BASIC, Level II BASIC, Model III BASIC, or TRSDOS BASIC clone. Programs that depend on PEEK, POKE, machine language, disk channels, graphics hardware, SOUND syntax, ON GOTO, or other undocumented features may require adaptation.

Contents71 / 136
TRS-80 MODEL 4 BASICPAGE 72

Error: ?SN ERROR

?SN ERROR indicates that a statement did not match the implemented grammar. Check spelling, required keywords, parentheses, commas, line numbers, and quotation marks. Unsupported historical BASIC statements also produce this error.

Contents72 / 136
TRS-80 MODEL 4 BASICPAGE 73

Runtime Error Reference

Important runtime messages include DIVISION BY ZERO, MOD BY ZERO, NO SUCH LINE, NEXT WITHOUT FOR, NEXT VARIABLE MISMATCH, RETURN WITHOUT GOSUB, READ PAST END OF DATA, NEGATIVE FACTORIAL, FACTORIAL TOO LARGE, ARRAY NOT DIMENSIONED, WRONG NUMBER OF SUBSCRIPTS, and SUBSCRIPT OUT OF RANGE.

Contents73 / 136
TRS-80 MODEL 4 BASICPAGE 74

Program: Horizontal Counter

This introductory program demonstrates FOR, NEXT, semicolon output, and a final blank PRINT.

10 CLS
20 FOR I=1 TO 20
30 PRINT I;" ";
40 NEXT I
50 PRINT
60 END
Contents74 / 136
TRS-80 MODEL 4 BASICPAGE 75

Program: Dice Roller

RANDINT produces an integer from one through six. Re-run the program for another roll.

10 CLS
20 PRINT "DICE ROLL: ";RANDINT(1,6)
30 END
Contents75 / 136
TRS-80 MODEL 4 BASICPAGE 76

Program: Guessing Game

This simple game selects a target and branches according to the player input.

10 A=RANDINT(1,10)
20 PRINT "GUESS 1 TO 10"
30 INPUT G
40 IF G=A THEN 100
50 PRINT "TRY AGAIN"
60 GOTO 30
100 PRINT "CORRECT"
110 END
Contents76 / 136
TRS-80 MODEL 4 BASICPAGE 77

Program: Multiplication Table

Nested loops and formatted PRINT create a compact multiplication table.

10 FOR R=1 TO 10
20 FOR C=1 TO 10
30 PRINT R*C,
40 NEXT C
50 PRINT
60 NEXT R
Contents77 / 136
TRS-80 MODEL 4 BASICPAGE 78

Program: Prime Number Test

The program counts exact divisors. It uses MOD and a loop.

10 INPUT N
20 C=0
30 FOR I=1 TO N
40 IF N MOD I=0 THEN 60
50 GOTO 70
60 C=C+1
70 NEXT I
80 IF C=2 THEN 110
90 PRINT "NOT PRIME"
100 END
110 PRINT "PRIME"
Contents78 / 136
TRS-80 MODEL 4 BASICPAGE 79

Program: Array Squares

This program dimension an array, fills it, and prints it.

10 DIM X(20)
20 FOR I=0 TO 20
30 X(I)=I*I
40 NEXT I
50 FOR I=0 TO 20
60 PRINT I;" ";X(I)
70 NEXT I
Contents79 / 136
TRS-80 MODEL 4 BASICPAGE 80

Program: Matrix Fill

A two-dimensional array stores products by row and column.

10 DIM A(5,5)
20 FOR R=0 TO 5
30 FOR C=0 TO 5
40 A(R,C)=R*C
50 NEXT C
60 NEXT R
70 PRINT A(4,5)
Contents80 / 136
TRS-80 MODEL 4 BASICPAGE 81

Program: String Array Menu

A string array stores labels that can be printed in a loop.

10 DIM M$(3)
20 M$(0)="RUN"
30 M$(1)="LIST"
40 M$(2)="SAVE"
50 M$(3)="BREAK"
60 FOR I=0 TO 3
70 PRINT I;" ";M$(I)
80 NEXT I
Contents81 / 136
TRS-80 MODEL 4 BASICPAGE 82

Program: Moving Star

PRINT @ and PAUSE create a simple moving character. Press BREAK to stop or allow it to finish.

10 CLS
20 FOR P=0 TO 63
30 PRINT @ P,"*"
40 PAUSE 50
50 PRINT @ P," "
60 NEXT P
Contents82 / 136
TRS-80 MODEL 4 BASICPAGE 83

Program: Random Histogram

The array counts 100 simulated die rolls and prints totals.

10 DIM C(6)
20 FOR I=1 TO 100
30 D=RANDINT(1,6)
40 C(D)=C(D)+1
50 NEXT I
60 FOR D=1 TO 6
70 PRINT D;" ";C(D)
80 NEXT D
Contents83 / 136
TRS-80 MODEL 4 BASICPAGE 84

Program: Data Reader

DATA, READ, and RESTORE provide an embedded table.

10 DATA 10,20,30,40
20 FOR I=1 TO 4
30 READ A
40 PRINT A
50 NEXT I
60 RESTORE
Contents84 / 136
TRS-80 MODEL 4 BASICPAGE 85

Program: Subroutine Demonstration

A reusable heading routine is called twice.

10 GOSUB 100
20 PRINT "FIRST SECTION"
30 GOSUB 100
40 PRINT "SECOND SECTION"
50 END
100 PRINT "----------------"
110 RETURN
Contents85 / 136
TRS-80 MODEL 4 BASICPAGE 86

Program: One-Dimensional Life

This cellular-automaton program demonstrates DIM, two arrays, random initialization, nested loops, array references in conditions, array assignments, GOTO, and repeated generations. It runs continuously because line 350 returns to initialization; use BREAK PROGRAM, the virtual BREAK key, Esc, or Ctrl+C to stop it.

5 LET M = 68
10 DIM X (M)
20 DIM Y (M)
30 FOR I = 0 TO M
40 LET R = RND(1) * 10
50 IF R > 5 THEN 80
60 LET X(I) = 1
70 GOTO 90
80 LET X(I) = 0
90 NEXT I
100 FOR I = 2 TO M-2
110 IF X(I) = 1 THEN 140
120 PRINT " ";
130 GOTO 150
140 PRINT "*";
150 NEXT I
160 PRINT
170 GOTO 200
200 FOR T = 0 TO 25
210 FOR I = 2 TO M-2
220 GOTO 500
230 NEXT I
260 FOR I = 0 TO M
270 LET X(I) = Y(I)
280 IF X(I) = 0 THEN 310
290 PRINT "*";
300 GOTO 320
310 PRINT " ";
320 NEXT I
330 PRINT
340 NEXT T
350 GOTO 30
500 LET C = 0
510 FOR Z = (I-2) TO (I+2)
520 IF Z = I THEN 550
530 IF X(Z) = 0 THEN 550
540 LET C = C + 1
550 NEXT Z
560 IF X(I) = 0 THEN 800
700 LET Y(I) = 0
710 IF C = 2 THEN 750
720 IF C = 4 THEN 750
730 GOTO 230
750 LET Y(I) = 1
760 GOTO 230
800 LET Y(I) = 0
810 IF C = 2 THEN 850
820 IF C = 3 THEN 850
830 GOTO 230
850 LET Y(I) = 1
860 GOTO 230
Contents86 / 136
TRS-80 MODEL 4 BASICPAGE 87

Adapting Historical Listings

Old magazine and manual listings may use syntax not implemented here. First preserve the original file, then replace unsupported commands one at a time. PEEK/POKE graphics can often be rewritten with PRINT @. Timing loops can become PAUSE. Disk file operations can be replaced by browser ASCII LOAD and SAVE for whole-program storage.

Contents87 / 136
TRS-80 MODEL 4 BASICPAGE 88

Backing Up Your Programs

Save frequently under versioned filenames such as LIFE01.BAS, LIFE02.BAS, and LIFE03.BAS. Plain ASCII files are small and easy to archive. Keep a known-working copy before changing loops, branch targets, or array dimensions.

Contents88 / 136
TRS-80 MODEL 4 BASICPAGE 89

Using Notepad++

Set the document to plain text and use a monospaced font. Keep line endings consistent. BASIC keywords may be uppercase for a period appearance, although the emulator matches keywords case-insensitively. Do not let smart-quote substitution change straight quotation marks.

Contents89 / 136
TRS-80 MODEL 4 BASICPAGE 90

Mobile and iPad Use

Tap the green screen to focus the hidden input control. The on-screen keyboard can enter common keys and function shortcuts. Local file loading and downloading depend on browser file-picker behavior. For long programs, editing on a desktop text editor and transferring the .BAS file is usually more comfortable.

Contents90 / 136
TRS-80 MODEL 4 BASICPAGE 91

Keyboard Shortcuts

F1 types LIST, F2 RUN, F3 NEW, F4 CLS, F5 PRINT, F6 GOTO, F7 INPUT, and F8 HELP on the on-screen keyboard. ENTER submits. BREAK interrupts execution. Esc interrupts a running program or clears a non-running input line. Ctrl+C interrupts execution. The physical keyboard adds Up/Down command-history recall; Left/Right cursor movement; Home/End movement to the beginning or end of the current line; Backspace to remove the character before the cursor; and Delete to remove the character at the cursor. Recalled commands remain fully editable before ENTER is pressed.

Contents91 / 136
TRS-80 MODEL 4 BASICPAGE 92

Quick Command Summary

Core commands include RUN, LIST, EDIT n, NEW, CLEAR, CLS, HELP, MEM, DIR/FILES, LOAD, SAVE, KILL/DELETE, RENAME, BASIC, and SYSTEM. Core statements include PRINT, INPUT, LET, DIM, REM, END, GOTO, IF...THEN, GOSUB, RETURN, FOR, NEXT, DATA, READ, RESTORE, and PAUSE. Browser controls add ASCII LOAD, ASCII SAVE, virtual-disk import/export, RESET / BOOT, and BREAK PROGRAM.

Contents92 / 136
TRS-80 MODEL 4 BASICPAGE 93

Quick Function Summary

Numeric functions: ABS, ASN, ACS, ATN, COS, EXP, FACT, FIX, INT, LOG, MAX, MIN, RANDINT, RND, ROUND, SGN, SIN, SQR, and TAN. String-related functions: LEN, ASC, VAL, CHR$, STR$, LEFT$, RIGHT$, MID$, UPPER$, LOWER$, and TRIM$. INKEY$ reports the last key.

Contents93 / 136
TRS-80 MODEL 4 BASICPAGE 94

Alphabetical Index A–G

ABS, ACS, AND, arrays, ASC, ASN, assignment, BASIC, BREAK, CATALOG, CHR$, CLEAR, CLS, comparisons, COS, DATA, DIM, DIR, EDIT, E, END, EXP, FACT, factorial, FALSE, FIX, FOR, GOSUB, GOTO.

Contents94 / 136
TRS-80 MODEL 4 BASICPAGE 95

Alphabetical Index H–P

HELP, IF, INKEY$, INPUT, INT, KILL, LEFT$, LEN, LET, LIST, LOG, LOWER$, MAX, MEM, MID$, MIN, MOD, NEW, NEXT, NOT, numeric variables, OR, PAUSE, PI, PRINT, PRINT @.

Contents95 / 136
TRS-80 MODEL 4 BASICPAGE 96

Alphabetical Index Q–Z

RANDINT, READ, REM, RENAME, RESTORE, RETURN, RIGHT$, RND, ROUND, RUN, SAVE, SAVE ASCII BASIC, INSTR, SGN, SIN, SQR, STEP, string arrays, string variables, STR$, SYSTEM, TAB, TAN, THEN, TRIM$, TRUE, UPPER$, VAL.

Contents96 / 136
TRS-80 MODEL 4 BASICPAGE 97

Final Notes

The best way to learn BASIC is to modify working programs. Change constants, add output, place values in arrays, create a subroutine, and intentionally trigger an error so you recognize it later. Save each successful stage. The emulator is designed to make experimentation safe: the BREAK control stops runaway programs, and ASCII files make your work portable.

Contents97 / 136
TRS-80 MODEL 4 BASICPAGE 98

INSTR String Search

INSTR searches one string for another and returns a 1-based character position. If the search text is not found, it returns 0. The updated web emulator supports the two-argument form used by the current emulator.

Syntax

INSTR(string, search)

Examples

PRINT INSTR("HELLO","LL")
A$="SATELLITE_DATABASE.HTML"
PRINT INSTR(A$,".HTML")

Result

INSTR("HELLO","LL") returns 3.

Contents98 / 136
TRS-80 MODEL 4 BASICPAGE 99

String Comparisons in IF...THEN

The updated emulator allows string expressions to be compared directly in IF conditions. This includes string variables and string functions such as LEFT$, RIGHT$, MID$, UPPER$, LOWER$, and TRIM$.

Syntax

IF string-expression = string-expression THEN lineIF string-expression <> string-expression THEN line

Supported comparisons

=, <>, <, <=, >, and >=.

Examples

10 A$="REPORT.TXT"
20 IF RIGHT$(A$,4)=".TXT" THEN 100
30 END
100 PRINT "TEXT FILE"
110 END
Contents99 / 136
TRS-80 MODEL 4 BASICPAGE 100

REM and Colon Handling

REM consumes the remainder of its BASIC line. In the updated emulator, a colon appearing after REM is treated as comment text rather than as a separator for another BASIC statement.

Example

10 PRINT "START"
20 REM INPUT FORMAT: ls.txt
30 PRINT "DONE"

The text : ls.txt remains part of the comment on line 20 and is not executed as a separate statement.

Colons outside quoted strings and outside REM comments continue to separate multiple BASIC statements on one line.
Contents100 / 136
TRS-80 MODEL 4 BASICPAGE 101

Enhanced Runtime Error Diagnostics

When a stored BASIC program fails at runtime, the updated emulator reports the BASIC line number, the exact statement that failed, and the statement index within the flattened program. This makes errors in long programs and colon-separated lines easier to locate.

Example diagnostic

?ERROR IN BASIC LINE 30: EXPECTED =
  STATEMENT: ls.txt
  STATEMENT INDEX: 4 OF 94

Direct-mode errors that are not associated with a stored BASIC line continue to use the shorter ?ERROR: form.

Contents101 / 136
TRS-80 MODEL 4 BASICPAGE 102

Virtual Drives: Drive 0 and Drive 1

The current emulator provides two virtual drives. Drive 0 is a server-shared disk backed by the Raspberry Pi server API, so files can be shared by different devices that open the same emulator. Drive 1 is browser-local IndexedDB storage and remains private to that browser/device.

Selecting a Drive

DRIVE 0DRIVE 1

Drive selection affects FILES, program LOAD/SAVE, file deletion/rename, and the drive captured by a BASIC OPEN statement.

Directory Commands

DIRFILESFILES *.BAS

FILES accepts * and ? wildcards.

Program File Commands

LOAD "DEMO.BAS"SAVE "MYPROG.BAS"KILL "MYPROG.BAS"DELETE "MYPROG.BAS"RENAME "OLD.BAS","NEW.BAS"
Drive 0 requires the server-side trs80_disk_api.php endpoint and a writable server disk directory. Drive 1 is local browser storage and is not automatically shared with another device.
Contents102 / 136
TRS-80 MODEL 4 BASICPAGE 103

Command History, Line Editing, and EDIT

The emulator provides modern command-line editing while retaining the Model 4 terminal appearance. Up to 100 submitted commands are retained in the current session history. Up and Down recall earlier or later commands. Recalled text can be changed before it is submitted again.

Editing Keys

KeyAction
Up / DownRecall previous or later command-history entries.
Left / RightMove the insertion cursor one character.
Home / EndMove to the beginning or end of the current input line.
BackspaceDelete the character immediately before the cursor.
DeleteDelete the character at the cursor.
Normal typingInsert new characters at the current cursor position.

EDIT n

EDIT 120

EDIT n is useful as a quick line editor. If BASIC line 120 exists, the emulator places the complete numbered line onto the editable command line. Move the cursor, delete or insert characters, and press ENTER to replace the stored line.

120 PRINT "HELLO WORLD"
EDIT 120

After EDIT 120, modify the recalled 120 PRINT ... text and press ENTER. This avoids creating a separate full-screen editor when ordinary line editing is sufficient.

Contents103 / 136
TRS-80 MODEL 4 BASICPAGE 104

Virtual Disk Backup and Restore

The EXPORT DISK and IMPORT DISK controls operate on the currently selected virtual drive. Export produces a JSON backup of the selected drive; import restores files from a compatible backup into the selected drive.

Typical Procedure

DRIVE 0
FILES
[click EXPORT DISK]

The exported filename identifies the selected drive. Before importing, select the destination drive with DRIVE 0 or DRIVE 1.

Import adds or replaces files represented in the backup. Keep separate backups of important programs and data files.
Contents104 / 136
TRS-80 MODEL 4 BASICPAGE 105

Shared Server Drive 0

Drive 0 is the emulator's shared server disk. The browser communicates with trs80_disk_api.php, allowing programs and data files saved from one device to be visible from another device using the same server.

Syntax

DRIVE 0

Examples

DRIVE 0
FILES
SAVE "TEST.BAS"
FILES
LOAD "TEST.BAS"

Server Requirement

The PHP disk API must be installed and the server disk directory must be writable by the web-server account. A server/API error is reported as a disk error by the emulator.

Related Entries

DRIVE 1, FILES, LOAD, SAVE, OPEN

Contents105 / 136
TRS-80 MODEL 4 BASICPAGE 106

Local Browser Drive 1

Drive 1 uses IndexedDB in the current browser. It persists through ordinary page reloads and browser restarts, but it is not automatically synchronized to another browser or device.

Syntax

DRIVE 1

Example

DRIVE 1
FILES *.BAS
SAVE "LOCAL.BAS"
Clearing site/browser storage can remove Drive 1. Use EXPORT DISK or ordinary ASCII BASIC export for important files.
Contents106 / 136
TRS-80 MODEL 4 BASICPAGE 107

OPEN and File Numbers

OPEN gives a BASIC program sequential access to a file on the drive that is selected when the statement executes. The emulator supports file numbers 1 through 16.

Syntax

OPEN "I",#1,"DATA.TXT"OPEN "O",#1,"DATA.TXT"OPEN "A",#1,"DATA.TXT"
ModeMeaning
IInput. Opens an existing file for sequential reading.
OOutput. Starts an output file; data is committed when the file is closed.
AAppend. Loads existing contents when present and writes new output at the end.

The selected drive is remembered by the open file handle. Changing drives after OPEN does not move that already-open handle to another drive.

Common Errors

Bad mode, file number outside 1–16, duplicate open file number, missing input file, or attempting an operation with the wrong file mode.

Contents107 / 136
TRS-80 MODEL 4 BASICPAGE 108

PRINT # Sequential Output

PRINT # writes evaluated BASIC output to a file opened in output or append mode.

Syntax

PRINT #1,"RICH"PRINT #1,12345PRINT #1,A$,N

Example

10 OPEN "O",#1,"PEOPLE.TXT"
20 A$="RICH"
30 N=65
40 PRINT #1,A$,N
50 CLOSE #1
60 END

A trailing comma or semicolon suppresses the normal line ending, following the emulator's PRINT-list behavior.

PRINT # requires a file opened with mode O or A.
Contents108 / 136
TRS-80 MODEL 4 BASICPAGE 109

INPUT # Sequential Input

INPUT # reads sequential fields from a file opened for input. Multiple variables may be supplied.

Syntax

INPUT #1,AINPUT #1,A$,N

Behavior

Quoted text is read as a string field. Unquoted fields are delimited by commas or line endings. Numeric variables are converted with numeric parsing; a value that cannot be parsed numerically becomes zero.

Example

10 OPEN "I",#1,"PEOPLE.TXT"
20 INPUT #1,A$,N
30 PRINT A$;N
40 CLOSE #1
50 END
Reading beyond available input produces an input-past-end-of-file error. Use EOF() when processing files of unknown length.
Contents109 / 136
TRS-80 MODEL 4 BASICPAGE 110

LINE INPUT #

LINE INPUT # reads an entire text line into a string variable without splitting the line into comma-separated fields.

Syntax

LINE INPUT #1,A$

Example

10 OPEN "I",#1,"NOTES.TXT"
20 IF EOF(1) THEN 60
30 LINE INPUT #1,A$
40 PRINT A$
50 GOTO 20
60 CLOSE #1
70 END

The destination must be a string variable.

Contents110 / 136
TRS-80 MODEL 4 BASICPAGE 111

EOF() and CLOSE

EOF() tests whether an input file has reached the end of its content. CLOSE releases open file handles and commits output/append data to the selected virtual drive.

EOF Syntax

EOF(1)EOF(#1)

The function returns a BASIC numeric truth value suitable for IF.

CLOSE Syntax

CLOSE #1CLOSE

CLOSE #1 closes one file. CLOSE closes all currently open BASIC files. Output and append files are written back when closed if they have been changed.

Recommended Pattern

10 OPEN "I",#1,"DATA.TXT"
20 IF EOF(1) THEN 60
30 LINE INPUT #1,A$
40 PRINT A$
50 GOTO 20
60 CLOSE #1
Contents111 / 136
TRS-80 MODEL 4 BASICPAGE 112

File I/O Programming Examples

The virtual drives can now hold both BASIC programs and ordinary sequential data files.

Create a Data File

10 OPEN "O",#1,"TEST.TXT"
20 PRINT #1,"RICH"
30 PRINT #1,12345
40 PRINT #1,"TRS-80 MODEL 4"
50 CLOSE #1
60 END

Read the Data File

10 OPEN "I",#1,"TEST.TXT"
20 LINE INPUT #1,A$
30 INPUT #1,N
40 LINE INPUT #1,B$
50 CLOSE #1
60 PRINT A$
70 PRINT N
80 PRINT B$
90 END

Append a Log Entry

10 OPEN "A",#2,"LOG.TXT"
20 PRINT #2,"PROGRAM STARTED"
30 CLOSE #2
40 END

Select DRIVE 0 before running when the file should be shared through the server, or DRIVE 1 for browser-local storage.

Contents112 / 136
TRS-80 MODEL 4 BASICPAGE 113

Clipboard, Paste, and Program Copy

The current emulator adds browser clipboard conveniences while retaining the terminal interface.

Paste BASIC Listings

Multi-line BASIC text can be pasted into the emulator. Numbered lines are processed as program lines, allowing a listing copied from an editor to be inserted without typing each line.

Copy

Selected terminal text can be copied with the normal browser copy operation. The emulator also provides a program-copy control for copying the stored BASIC listing.

Ctrl+C

When terminal text is selected, Ctrl+C performs normal copying. When no text is selected during program execution, Ctrl+C remains available as a BREAK request.

Browser clipboard permission behavior varies. The emulator's paste/copy controls may require a user click and an HTTPS or localhost context in some browsers.
Contents113 / 136
TRS-80 MODEL 4 BASICPAGE 114

Current Compatibility and Feature Summary

This edition documents the current HTML emulator, including the compatibility work added to run programs that also run in the C interpreter.

Language and Parser Updates

  • Multi-character scalar variables such as YY, COUNT, and string names ending in $.
  • Nested numeric functions and expressions, including expressions such as 11+INT(A).
  • Inline IF...THEN...ELSE statements, including assignments and PRINT statements in either branch.
  • String comparisons in IF conditions.
  • INSTR() string searching.
  • REM-aware colon handling and enhanced runtime error diagnostics.

Terminal and Storage Updates

  • 64-column by 16-row positioned screen behavior for PRINT @ programs such as the fitted sine-wave demonstration.
  • Up/Down command history and Left/Right/Home/End line editing.
  • EDIT n to recall a stored BASIC line onto the editable command line.
  • Clipboard paste/copy support.
  • Drive 0 server-shared storage and Drive 1 browser-local storage.
  • Sequential BASIC file I/O with OPEN, CLOSE, PRINT #, INPUT #, LINE INPUT #, and EOF().
  • Server-backed sequential tape data I/O using TAPE:name filenames, a separate tape PHP API, physical trs80_tape storage, buffered large-file writes, and animated tape motion.
  • Cassette BASIC program storage with CLOAD, CSAVE, CLOAD?/TAPE, REWIND/TREW, and TSTOP.
  • RENUM program renumbering with automatic branch-target adjustment.
  • PRINT USING numeric and string formatting.

Help Manual Address

The emulator's Help Manual links should point to trs80_model4_manual.html, the filename of this manual.

Contents114 / 136
TRS-80 MODEL 4 BASICPAGE 115

TYPE Command

TYPE displays a readable file directly from a virtual drive without loading it into BASIC program memory.

Syntax

TYPE filenameTYPE "filename"TYPE 0:filenameTYPE 1:filename

Examples

DRIVE 0
TYPE TEST.TXT
TYPE 0:TEST.TXT
TYPE "1:README.TXT"
TYPE 0:PROGRAM.BAS

Without a drive prefix, TYPE uses the current drive. TYPE does not change the BASIC program in memory; LIST still lists the program currently in memory.

TYPE is intended for text. Binary files can contain control characters and should normally be moved with COPY, GET, EXPORT, PUT, or IMPORT.
Contents115 / 136
TRS-80 MODEL 4 BASICPAGE 116

COPY Between Virtual Drives

COPY copies a file without loading or interpreting it as BASIC. This is useful for moving files between shared Drive 0 and browser-local Drive 1.

Syntax

COPY "source","destination"

Examples

COPY "0:TEST.BAS","1:TEST.BAS"
COPY "1:SINEWAVE.BAS","0:SINEWAVE.BAS"
COPY "1:TEST.BAS","0:BACKUP.BAS"

The last example copies the file and gives the destination a different name.

Contents116 / 136
TRS-80 MODEL 4 BASICPAGE 117

PC to Virtual Drive: PUT / IMPORT

PUT and IMPORT open the browser file picker and copy the selected PC file to the currently selected virtual drive. The PC → DRIVE button performs the same operation.

Examples

DRIVE 0
PUT
FILES

DRIVE 1
IMPORT
FILES

The original PC filename is used on the virtual drive. The operation is not limited to .BAS files.

Contents117 / 136
TRS-80 MODEL 4 BASICPAGE 118

Virtual Drive to PC: GET / EXPORT

GET and EXPORT download one virtual-drive file to the PC. The DRIVE → PC button provides the same operation through a prompt.

Examples

GET 0:PROGRAM.CMD
GET 1:DATA.DAT
EXPORT 0:PROGRAM.CMD

Round Trip

DRIVE 0
PUT
FILES
COPY "0:PROGRAM.CMD","1:PROGRAM.CMD"
GET 1:PROGRAM.CMD
Contents118 / 136
TRS-80 MODEL 4 BASICPAGE 119

Binary and Non-BASIC Files

PC import/export uses raw byte data so the virtual drives can store files other than BASIC source.

Examples

PROGRAM.CMD
UTILITY.BIN
ROMIMAGE.ROM
DISK.IMG
RECORDS.DAT
NOTES.TXT
PROGRAM.BAS

PUT/IMPORT reads the PC file as bytes. GET/EXPORT reconstructs those bytes for download. COPY transfers the stored contents between virtual drives without parsing them as BASIC.

Storage does not imply execution. A CMD, ROM, BIN, or disk image can be stored and transferred even if the BASIC interpreter cannot execute or mount that format. Avoid TYPE on binary files because their byte values may represent terminal control characters.
Contents119 / 136
TRS-80 MODEL 4 BASICPAGE 120

CR/LF and Current Command Summary

The current emulator fixes sequential text output so PRINT # stores actual carriage-return/line-feed characters (CR/LF), not printable backslash-r/backslash-n text.

Example

10 OPEN "O",#1,"TEST.TXT"
20 PRINT #1,"RICH"
30 PRINT #1,12345
40 PRINT #1,"TRS-80 MODEL 4"
50 CLOSE #1
60 END

TYPE TEST.TXT should display the three values on separate lines. TYPE also normalizes legacy printable \r\n sequences created by older builds.

Virtual Drive Commands

DRIVE 0
DRIVE 1
DIR
FILES [pattern]
LOAD "PROGRAM.BAS"
SAVE "PROGRAM.BAS"
TYPE "FILE.TXT"
COPY "0:SOURCE","1:DEST"
KILL "FILE"
DELETE "FILE"
RENAME "OLD","NEW"
PUT
IMPORT
GET 0:FILE
EXPORT 1:FILE

BASIC Sequential File I/O

OPEN "I",#1,"FILE"
OPEN "O",#1,"FILE"
OPEN "A",#1,"FILE"
PRINT #1,...
INPUT #1,...
LINE INPUT #1,A$
EOF(1)
CLOSE #1
CLOSE
This manual corresponds to trs80_model4.html.
Contents120 / 136
TRS-80 MODEL 4 BASICPAGE 121

Level II BASIC Compatibility

The current emulator includes additional compatibility work prompted by testing an original 1979 TRS-80 BIORHYTHM program. The goal is to accept authentic source syntax rather than require old programs to be rewritten for the browser interpreter.

Compatibility Additions

  • REM: comments consume the remainder of the BASIC line.
  • CLEAR n syntax is accepted.
  • DEFINT and DEFDBL declarations are accepted for source compatibility.
  • Prompted INPUT accepts authentic syntax such as INPUT"MONTH (1 TO 12)";M.
  • NEXT may omit the FOR variable.
  • STR$() supplies the leading blank expected for positive values by Microsoft/Radio Shack BASIC programs.
  • Compound AND/OR IF conditions are supported.
  • INKEY$ is available for nonblocking keyboard checks.
  • CHR$(131) and CHR$(149) receive visible browser approximations for the semigraphics used by the BIORHYTHM chart.
  • TAB() now accounts for characters already produced earlier in the same PRINT statement.
Contents121 / 136
TRS-80 MODEL 4 BASICPAGE 122

REM and Colon Parsing

On Level II BASIC, once a REM statement begins, the remainder of that physical BASIC line is comment text. A colon inside that comment must not be interpreted as a statement separator.

Authentic Examples

100 REM: BIORHYTHM
110 REM: COPYRIGHT 1979 BY TOM RUGG AND PHIL FELDMAN

Earlier emulator builds split these lines at the colon and attempted to execute BIORHYTHM as another statement, producing a syntax error. The statement splitter now recognizes REM: and ignores the remainder of the line as executable BASIC.

Do not remove the colon from old source programs merely to satisfy the emulator. The current parser is intended to accept the original form.
Contents122 / 136
TRS-80 MODEL 4 BASICPAGE 123

INPUT, CLEAR, DEFINT and DEFDBL

Prompted INPUT

The parser accepts the original compact Level II syntax with no required space after INPUT:

505 INPUT"MONTH (1 TO 12)";M
520 INPUT"DAY (1 TO 31)";D
540 INPUT"YEAR";Y

The spaced form is also accepted.

CLEAR

CLEAR 200

On the original machine the numeric argument is associated with BASIC memory/string-space management. The browser interpreter does not require the same physical memory reservation, so the syntax is accepted for compatibility.

Type Declarations

DEFINT K,L
DEFDBL B,J,M-Z

These declarations are accepted so original source can run. The browser's JavaScript numeric representation does not reproduce every internal storage distinction of the original machine.

Contents123 / 136
TRS-80 MODEL 4 BASICPAGE 124

STR$, Logical Conditions and NEXT

STR$ Positive-Number Formatting

Programs may depend on the leading blank returned for a positive number. The BIORHYTHM date formatter does exactly this:

1080 A$=STR$(M):W=LEN(A$)-1
1090 C$=MID$(A$,2,W)+"/"

The current emulator preserves that leading blank for positive STR$() results.

AND / OR Conditions

510 M=INT(M):IF M<1 OR M>12 THEN 505
950 IF A$="P" OR A$="E" OR A$="*" THEN C$="*"

Logical operators are evaluated around relational conditions so compound numeric and string tests can be used in IF statements.

NEXT Without a Variable

270 FOR K=1 TO 1000:NEXT

The variable after NEXT is optional, matching the source style used by the original program.

Contents124 / 136
TRS-80 MODEL 4 BASICPAGE 125

INKEY$ and TRS-80 Graphics Characters

INKEY$

INKEY$ permits a running BASIC program to test the keyboard without issuing an INPUT prompt.

370 PRINT"PRESS 'E' TO END, SPACE TO CONTINUE";
380 R$=INKEY$:IF R$="" THEN 380
390 IF R$="E" THEN 120

Semigraphics Character Approximation

The BIORHYTHM listing uses CHR$(131) and CHR$(149) while constructing its chart. A modern browser does not use the original TRS-80 video character generator, so the emulator maps these values to visible line-character approximations for the chart display.

750 FOR K=1 TO T+T+1:PRINT CHR$(131);:NEXT
880 L$=LEFT$(L$,T)+CHR$(149)+RIGHT$(L$,T)
These are visual approximations, not a byte-for-byte reproduction of the original TRS-80 character ROM glyphs.
Contents125 / 136
TRS-80 MODEL 4 BASICPAGE 126

TAB() and BIORHYTHM Compatibility

The BIORHYTHM chart exposed an important PRINT/TAB positioning problem. The date is printed with:

350 PRINT C$;TAB(8);L$

Earlier builds calculated TAB(8) from the terminal column that existed before the PRINT statement began. That ignored characters already generated by C$ in the same PRINT statement. The error became visible when the displayed date changed length, such as the transition from 10/9/26 to 10/10/26.

Current Behavior

TAB positioning now includes the text already generated earlier in the current PRINT statement. This keeps the chart data aligned instead of allowing a longer date to shift the plotted line unexpectedly.

BIORHYTHM Regression Test

The original 1979 program is used as a compatibility test for REM parsing, prompted INPUT, CLEAR/DEF declarations, FIX, INKEY$, STR$, string functions, logical OR, NEXT, semigraphics approximations, and PRINT/TAB behavior.

This manual corresponds to the current emulator file trs80_model4.html.
Contents126 / 136
TRS-80 MODEL 4 BASICPAGE 127

DATE$ and TIME$

DATE$ and TIME$ return the current local date and time from the computer, tablet, or phone running the web emulator. They are read-only string values and may be used anywhere the emulator accepts a string expression.

Purpose

Provides the current local calendar date and clock time to BASIC programs and direct-mode commands.

Syntax

PRINT DATE$PRINT TIME$D$=DATE$T$=TIME$

Returned Formats

FunctionFormatExample
DATE$MM/DD/YYYY10/01/2026
TIME$HH:MM:SS, 24-hour clock14:35:08

Detailed Description

Each reference is evaluated when it is used. DATE$ reads the browser device's local calendar date and formats the month and day as two digits and the year as four digits. TIME$ reads the same device clock and returns two-digit hours, minutes, and seconds using a 24-hour clock.

Because these values come from the host device, their accuracy depends on that device's date, time, and time-zone settings. The emulator does not maintain a separate TRS-80 real-time clock.

Programming Guidance

  • Use DATE$ and TIME$ directly in PRINT statements for timestamps.
  • Assign them to string variables when a program needs to preserve a particular reading for later use.
  • Read TIME$ again when a fresh clock value is required; a previously assigned variable does not automatically update.

Examples

PRINT DATE$
PRINT TIME$

10 PRINT "DATE: ";DATE$
20 PRINT "TIME: ";TIME$
30 END

10 D$=DATE$
20 T$=TIME$
30 PRINT "STARTED ";D$;" AT ";T$
40 END

Related Entries

Emulator extension: These values are supplied by the browser environment and describe the device running the emulator.
Contents127 / 136
TRS-80 MODEL 4 BASICPAGE 128

Tape System Overview

The current emulator provides cassette/reel-to-reel emulation for BASIC program storage and sequential BASIC data files. Sequential files addressed with the TAPE: prefix are stored through the separate server tape API in the physical trs80_tape directory. The animated transport shows tape activity and a six-digit counter.

Two Tape Uses

UseCommandsPurpose
BASIC program storageCSAVE, CLOAD, CLOAD?Records, retrieves, and catalogs numbered BASIC programs.
Sequential data filesOPEN, PRINT #, INPUT #, LINE INPUT #, EOF(), CLOSEWrites and reads potentially large sequential data files using TAPE:name.

Server Storage Layout

/var/www/html/trs80_disk/      Drive 0 files
/var/www/html/trs80_tape/      Sequential tape data files
/var/www/html/trs80_disk_api.php
/var/www/html/trs80_tape_api.php

Drive 0 and tape storage use separate PHP APIs. Drive 1 remains browser-local storage.

Important: the BASIC-program cassette catalog and sequential TAPE: data files are different tape uses. A large data file written with OPEN "O",#n,"TAPE:name" is not a BASIC program and therefore is not expected to appear as a program in CLOAD?.
Tape timing, the six-digit counter, and reel motion are simulated. Large sequential jobs are optimized so visual tape activity does not require one physical server request for every BASIC record.
Contents128 / 136
TRS-80 MODEL 4 BASICPAGE 129

CLOAD and CSAVE

CSAVE records the BASIC program in memory to tape. CLOAD retrieves a BASIC program from tape and replaces the current in-memory listing.

Syntax

CSAVE "NAME"CSAVE NAME CLOAD "NAME"CLOAD NAMECLOAD

Behavior

Example

10 PRINT "HELLO FROM TAPE"
20 END
CSAVE "HELLO"
NEW
CLOAD "HELLO"
LIST
RUN

Sequential Example

REWIND
CLOAD
LIST
CLOAD
LIST
Saving a BASIC program to Drive 0/1 with SAVE and recording it to tape with CSAVE are separate operations.
Contents129 / 136
TRS-80 MODEL 4 BASICPAGE 130

Tape Catalog, Position, Rewind, Stop, and Eject

The tape transport has direct commands and on-screen controls. The counter is six digits so long operations can be observed without quickly wrapping.

BASIC Program Catalog

CLOAD?

CLOAD? catalogs BASIC programs recorded for CSAVE/CLOAD. It is a program catalog, not a directory of sequential TAPE: data files. Therefore a file such as TAPE:3LEDATA can exist and contain many thousands of records while CLOAD? still reports NO PROGRAMS RECORDED.

Tape Directory

TAPETAPE DIR

The current server-backed tape-data implementation uses the separate tape API and the trs80_tape directory for sequential data files.

Rewind

REWINDTREW

Rewind moves the simulated transport back to the beginning and resets the tape position/counter. Rewinding does not erase a recorded server tape-data file.

Stop

TSTOPSTOP TAPE

Stops the simulated transport. The STOP button performs the same operation.

PLAY and EJECT Buttons

PLAY starts visible transport motion. Use EJECT deliberately according to the current cassette-control implementation.

Do not use CLOAD? as a test for whether a sequential TAPE: data file exists. It reports BASIC program recordings.
Contents130 / 136
TRS-80 MODEL 4 BASICPAGE 131

BASIC Tape Data Files

A running BASIC program can use sequential file statements with a filename beginning with TAPE:. These data files are stored on the web server through trs80_tape_api.php, separately from Drive 0.

Open Modes

OPEN "O",#1,"TAPE:DATA" OPEN "I",#1,"TAPE:DATA" OPEN "A",#1,"TAPE:DATA"
ModeMeaning
OOutput: create/replace the named tape data file.
IInput: read an existing tape data file sequentially.
AAppend: retain existing contents and add new records at the end.

Data Statements

PRINT #1,expression INPUT #1,N INPUT #1,A$,N LINE INPUT #1,A$ IF EOF(1) THEN ... CLOSE #1

The physical server file is kept under /var/www/html/trs80_tape/. The directory must be writable by the web server account (normally www-data on the Raspberry Pi).

sudo mkdir -p /var/www/html/trs80_tape
sudo chown www-data:www-data /var/www/html/trs80_tape
sudo chmod 775 /var/www/html/trs80_tape

Tape reads/writes update the simulated transport and counter. Large output is buffered so records can be committed to the server in groups rather than by issuing an HTTP request for every record.

Reading beyond available data raises INPUT PAST END OF FILE. Use EOF() when the record count is not known, and always CLOSE output files so pending buffered data is committed.
Contents131 / 136
TRS-80 MODEL 4 BASICPAGE 132

Tape Data I/O Examples and Large Files

Write and Read Two Values

10 OPEN "O",#1,"TAPE:DATA"
20 PRINT #1,"RICH"
30 PRINT #1,12345
40 CLOSE #1
50 OPEN "I",#1,"TAPE:DATA"
60 INPUT #1,A$
70 INPUT #1,N
80 CLOSE #1
90 PRINT "NAME = ";A$
100 PRINT "NUMBER = ";N
110 END

Copy a Large Disk File to Tape

10 OPEN "I",#1,"3LE.TXT"
20 OPEN "O",#2,"TAPE:3LEDATA"
30 I=0
40 INPUT #1,A$
50 PRINT #2,A$
60 I=I+1
70 IF EOF(1) THEN CLOSE: PRINT I;" RECORDS WRITTEN": END
80 GOTO 40

This form avoids printing a progress message for every record. Screen output inside a 90,000-record loop can dominate execution time even when tape output itself is buffered.

Read Until End of Tape File

10 OPEN "I",#1,"TAPE:DATA"
20 IF EOF(1) THEN 60
30 INPUT #1,N
40 PRINT N
50 GOTO 20
60 CLOSE #1
70 END

Performance Notes

Contents132 / 136
TRS-80 MODEL 4 BASICPAGE 133

RENUM Program Renumbering

RENUM renumbers stored BASIC lines and adjusts supported line-number references so a program can be reorganized without manually repairing ordinary branches.

Syntax

RENUM RENUM newStart RENUM newStart,oldStart,increment

Defaults

RENUM is equivalent to starting new numbering at 10, considering the program from the beginning, and using an increment of 10.

ParameterDescription
newStartFirst new line number. Default 10.
oldStartOnly old lines at or above this value are selected for renumbering. Default 0.
incrementSpacing between new line numbers. Default 10.

Examples

RENUM
RENUM 100
RENUM 100,50,10
RENUM changes the program in memory. Save a backup before renumbering a valuable listing.
Contents133 / 136
TRS-80 MODEL 4 BASICPAGE 134

RENUM Branch-Target Rules and Examples

When a line number changes, RENUM also updates the supported numeric targets found in ordinary branch statements. Numbers inside quoted strings and REM comments are not intended as branch targets and are left alone.

Adjusted References

Example Before

5 PRINT "START"
7 GOSUB 25
12 IF A=1 THEN 30
20 GOTO 40
25 PRINT "SUB"
27 RETURN
30 PRINT "YES"
40 END

After RENUM

10 PRINT "START"
20 GOSUB 50
30 IF A=1 THEN 60
40 GOTO 80
50 PRINT "SUB"
60 RETURN
70 PRINT "YES"
80 END

Partial Renumbering

RENUM 100,50,10 leaves lines below old line 50 unchanged and renumbers selected lines beginning at 100. References to lines that are actually remapped are adjusted.

The renumbering routine contains future-compatible recognition for ON...GOTO/GOSUB target lists, but the current BASIC executor does not document ON...GOTO/GOSUB as an executable language feature. Do not rely on that statement merely because RENUM can recognize its target-list form.
Contents134 / 136
TRS-80 MODEL 4 BASICPAGE 135

PRINT USING

PRINT USING provides formatted numeric and string output. It is useful for financial reports, aligned tables, fixed decimal places, signs, currency, and scientific notation.

Syntax

PRINT USING "format";value PRINT USING "format";A;B;C

Numeric Format Characters

PatternUse
#Numeric digit position.
.Decimal point; following # positions determine decimal places.
,Thousands grouping when included in the format.
+ / -Leading or trailing sign control.
**Asterisk fill.
$$Currency prefix.
^^^^Scientific notation.

String Formats

Examples

10 A=1234.5
20 PRINT USING "########.##-";A
30 PRINT USING "$$####.##";A
40 PRINT USING "^^^^";A
50 A$="MODEL 4"
60 PRINT USING "&";A$

A trailing comma or semicolon on the PRINT USING value list suppresses the normal newline in the same spirit as the emulator's PRINT handling.

Contents135 / 136
TRS-80 MODEL 4 BASICPAGE 136

Current Emulator Command Checklist

This checklist includes the current shared/local disk arrangement and the server-backed sequential tape-data changes.

Program and Editing

RUN   LIST   EDIT n   RENUM   NEW   CLEAR   CLS
HELP  MEM    BASIC    SYSTEM

Virtual Drives

DRIVE 0          server-shared drive through trs80_disk_api.php
DRIVE 1          browser-local drive
DIR / CATALOG
FILES [pattern]
LOAD "file"
SAVE "file"
TYPE "file"
COPY "source","destination"
KILL "file" / DELETE "file"
RENAME "old","new"
PUT / IMPORT
GET file / EXPORT file

The Drive 0 PHP API contains the server-side import-size limit. On the current Raspberry Pi installation this was increased from 1 MiB to 50 MiB so multi-megabyte files such as TLE catalogs can be imported.

Tape Program Storage and Transport

CLOAD [name]
CSAVE [name]
CLOAD?             BASIC-program cassette catalog
TAPE / TAPE DIR
REWIND / TREW
TSTOP / STOP TAPE

Server-Backed Sequential Tape Data

OPEN "I",#n,"TAPE:name"
OPEN "O",#n,"TAPE:name"
OPEN "A",#n,"TAPE:name"
PRINT #n,...
INPUT #n,...
LINE INPUT #n,A$
EOF(n) / EOF(#n)
CLOSE #n / CLOSE

Server API:       /trs80_tape_api.php
Physical files:   /var/www/html/trs80_tape/

CLOAD? reports BASIC program recordings; it should not be interpreted as a directory of sequential TAPE: data files.

Language Features Confirmed in the Current Build

Numbered program lines; multi-character numeric and string variables; arrays; LET/assignment; PRINT; PRINT USING; PRINT @; TAB(); INPUT including prompted Level-II-style forms; IF...THEN...ELSE; GOTO; GOSUB/RETURN; FOR/NEXT including NEXT without a variable; DATA/READ/RESTORE; REM-aware colon handling; PAUSE; INKEY$; DATE$; TIME$; math, logical, string, and random functions documented elsewhere in this manual.

Compatibility Declarations

DEFINT
DEFSNG
DEFDBL
DEFSTR
CLEAR n

The DEF type declarations are accepted for source compatibility; JavaScript number/string storage does not reproduce every historical Microsoft BASIC numeric storage distinction.

Not a full TRSDOS or hardware emulator: this manual documents the behavior implemented by the current browser BASIC emulator.
Contents136 / 136