Skip to content

d/BASIC quick reference

This page is the cheat sheet: compact tables of d/BASIC's syntax for when you remember the idea but not the spelling. d/BASIC is the BASIC of d/OS, the operating system that brings modern software to 8-bit home computers such as the Atari 800, the Commodore 64 and the Apple II. Each section links to the chapter that teaches the idea and covers its edge cases; if you are new to d/BASIC, start with those chapters and come back here later.

Source rules

Construct Form
statement end newline
statement separator :
numbered line 10 statement
named label Name:
comment ' text or REM text
name case ASCII case-insensitive
identifier letter, then letters/digits/_; dotted components allowed
name length 40 characters per dotted component
string literal "text", maximum 32,767 bytes
decimal integer / real 42, 3.5, .625
exponent 1.2E6 (SINGLE) or 1.2D30 (DOUBLE)
literal suffix %, &, @, !, # forces the numeric type
hex literal &HFF
octal literal &O377 or classic &377

Whitespace separates keywords from names. FOR I is two tokens; FORI is one identifier.

Types

Type Suffix Width/shape
INTEGER % signed 16-bit
LONG & signed 32-bit
DECIMAL @ signed 64-bit fixed point, four fractional digits
SINGLE ! IEEE binary32; default numeric type
DOUBLE # IEEE binary64
STRING $ counted variable-length text
STRING * n — fixed-width record field, 1..65535 bytes
named TYPE — inline value record
named CLASS — counted object reference

When a number is converted to a wider type, the order is INTEGER → LONG → DECIMAL → SINGLE → DOUBLE.

False is 0; true is -1.

Declarations and storage

Purpose Syntax
scalar DIM Name [AS Type]
several names DIM A AS INTEGER, B AS LONG
array DIM A(upper) [AS Type]
explicit array bounds DIM A(lower TO upper [, ...]) [AS Type]
implicit array first undeclared A(index [, ...]) creates each dimension as OPTION BASE TO 10
module shared DIM SHARED Name [AS Type]
module shared array DIM SHARED A(bounds) [AS Type]
procedure shared alias SHARED Name [AS Type] [, ...] or SHARED A() [AS Type] [, ...]
persistent local STATIC Name [AS Type] [, ...]
persistent whole-array local STATIC A() [AS Type]
resize REDIM [PRESERVE] A(bounds) [AS Type]
release array ERASE A [, B...]
constant CONST Name = value [, Name = value...]
default type ranges DEFINT letter[-letter] [, ...] (also DEFLNG, DEFSNG, DEFDBL, DEFSTR)
default lower bound OPTION BASE 0 or OPTION BASE 1
RAM-only memory ceiling OPTION TIER RAM

REDIM PRESERVE does not work on an array of TYPE records; the compiler stops and says so. Ordinary REDIM can replace such an array all at once.

See Variables, DIM & Memory for initialization, scope, lifetime, arrays, and the difference between declaring a variable and constructing an object.

Assignment

[LET] destination = expression
SET objectDestination = expression
property += expression
SWAP left, right
MID$(target$, start [, length]) = replacement$

SET is an optional way to spell an object assignment. += adds to a property in place. SWAP exchanges two values, or two records of compatible type. MID$ on the left of = overwrites part of an existing string; it is different from the MID$() function.

Decisions

IF condition THEN
  statements
[ELSEIF condition THEN
  statements]
[ELSE
  statements]
END IF
IF condition THEN statement [ELSE statement]
IF condition THEN lineNumber
IF condition GOTO target
SELECT CASE expression
  CASE value [, value...]
  CASE low TO high
  CASE IS relation value
  CASE ELSE
END SELECT

Loops

FOR counter = start TO limit [STEP amount]
  statements
NEXT [counter [, counter...]]
WHILE condition
  statements
WEND
DO [WHILE condition | UNTIL condition]
  statements
LOOP [WHILE condition | UNTIL condition]

Exits: EXIT FOR, EXIT WHILE, EXIT DO, EXIT SUB, EXIT FUNCTION.

Classic branches

Statement Syntax
jump GOTO target
subroutine GOSUB target
return RETURN
computed jump ON expression GOTO target [, ...]
computed subroutine ON expression GOSUB target [, ...]
refusal handler ON REFUSAL GOTO target
refusal fields ERR, ERL
continue after refusal RESUME NEXT
resume at target RESUME target

A target is a numbered line or named label.

ERR is the error code and ERL the source line it belongs to. In d/BASIC an operation that cannot go ahead is said to be refused: it stops and says why. Errors found while compiling or loading happen before the program runs and cannot be caught inside it; ON REFUSAL handles the ones that happen while it runs. See Errors, Refusals & Diagnostics.

Procedures

DECLARE SUB Name ([parameters])
DECLARE FUNCTION Name ([parameters]) [AS Type]
SUB Name ([parameters]) [STATIC]
  statements
END SUB
FUNCTION Name ([parameters]) [AS Type] [STATIC]
  Name = result
END FUNCTION

A parameter that is a single value, a record or an object:

[BYREF | BYVAL] Name [AS Type]

A parameter that is a whole array:

[BYREF] Name() [AS Type]

Parameters of a SUB, FUNCTION or method are BYREF (passed by reference) unless you say BYVAL. At the call, BYVAL X or the classic extra parentheses (X) pass a copy of a value, a record or an object reference. A whole array is always shared with the procedure and cannot be BYVAL. WEAK may appear only on an object's field, never on a parameter.

Argument kind BYVAL BYREF
numeric scalar copies the value aliases the caller's variable
STRING copies the string value aliases the caller's string binding
TYPE record copies the complete record aliases the caller's record
CLASS reference copies the reference; both references may reach the same object aliases the caller's reference binding, so the callee may replace it
whole array A() forbidden shares the array binding and its elements

Calls:

CALL Name(arguments)
Name arguments
Name(arguments)

Expression function:

DEF FNName(parameters) = expression

A DEF FN function receives copies of its arguments, regardless of the BYREF default for ordinary procedures.

See Procedures & Functions for call-site overrides and worked examples.

Strings and text

Purpose Form
concatenate left$ + right$
length in bytes LEN(text$)
prefix / suffix / slice LEFT$(text$, n), RIGHT$(text$, n), MID$(text$, start [, count])
find a substring INSTR([start,] text$, sought$)
repeat a string / byte STRING$(count, text$) or STRING$(count, code)
spaces SPACE$(count)
change case LCASE$(text$), UCASE$(text$)
trim edges LTRIM$(text$), RTRIM$(text$)
byte/code conversion ASC(text$), CHR$(code)
number to text STR$(number)
text to number VAL(text$)
fixed-width field Field AS STRING * n inside a TYPE

String positions and lengths count bytes, not characters. See Strings & Text for clamping rules, UTF-8 boundaries, conversions, and writing into a string with MID$.

Arrays

Operation Syntax
element A(index [, ...])
first bound LBOUND(A [, dimension])
last bound UBOUND(A [, dimension])
independent copy ARRAYCOPY Source() TO Destination()
uniform fill ARRAYFILL Destination(), Value
binding exchange ARRAYSWAP A(), B()

The three whole-array statements need the bare A() form, with nothing inside the parentheses. They work on arrays of numbers, variable-length STRINGs and CLASS references, not on arrays of TYPE records. See Arrays.

Console and program data

Purpose Syntax
output PRINT [items]
zones PRINT A, B
concatenate/suppress newline PRINT A; B;
column PRINT TAB(n); value
spaces PRINT SPC(n); value
formatted numeric PRINT USING "one numeric field"; value
converted input INPUT ["prompt" {; | ,}] target [, ...]
whole line LINE INPUT ["prompt" {; | ,}] target$
embedded values DATA value [, ...]
consume values READ target [, ...]
rewind data RESTORE [target]
random seed RANDOMIZE [expression]
complete END (status 0)
interrupt STOP (status 3)
raise governed error ERROR literalRuleId (1..65535)

The DATA statement above builds a table into the program. It has nothing to do with the database requests, also named DATA, listed further down this page.

ERROR takes a literal number, and being able to write a number does not make it yours: an error code in a shipped program must come from d/BASIC's registered list of codes. 61440..65534 is reserved for private experiments and must not ship, 0 means no error, and 65535 is never assigned. See Errors, Refusals & Diagnostics.

Files and file manipulation

File operations are intents. An intent is a named request, such as "fill this rectangle" or "list this directory", that the machine carries out however it can.

FILE Intent Purpose
FILE.QUERY_MOUNT inspect one requested mount and read its capabilities, state, limits, latency class, and mount count
FILE.LIST fetch a bounded, filtered directory page and its generation
FILE.STAT inspect kind, size, flags, and containing-directory generation
FILE.OPEN open for READ, staged CREATE, APPEND, or staged REPLACE
FILE.READ read a bounded byte span at an explicit offset
FILE.WRITE write a bounded byte span at an explicit offset and report progress
FILE.CLOSE close a read handle, commit a staged write atomically, or abandon it
FILE.EDIT DELETE, TRASH, RESTORE, RENAME, same-mount MOVE, or MKDIR

FILE is bytes at a name. Moving a file between two mounts is deliberately a copy followed by a delete; d/BASIC does not pretend such a move happens in one step. See Files & File Manipulation.

Database and DATA Intents

DATA family Operations
capabilities and values QUERY_CAPS, OPEN, GET_VALUE, CLOSE
immutable query snapshots OPEN_SNAPSHOT, FETCH_PAGE, RESOLVE_ROW, REVALIDATE_OBJECT, ACCEPT_EXACT, CLOSE_SNAPSHOT
database writes and attachments QUERY_WRITE_CAPS, OPEN_WRITE, BEGIN_WRITE, BEGIN_ATTACHMENT, WRITE_ATTACHMENT_CHUNK, FINISH_ATTACHMENT, COMMIT_WRITE, WRITE_STATUS, ABORT_WRITE, CLOSE_WRITE
durable artifact writes QUERY_ARTIFACT_CAPS, BEGIN_NEW, BEGIN_SAVE, BEGIN_SAVE_AS, BEGIN_PUBLISH, WRITE_ARTIFACT_CHUNK, FINISH_ARTIFACT, COMMIT_ARTIFACT, ARTIFACT_STATUS, ABORT_ARTIFACT, CLOSE_ARTIFACT, ACK_ARTIFACT_RECEIPT
artifact retirement and reads BEGIN_RETIRE, ALLOCATE_ARTIFACT_OPERATION, LIST_ARTIFACTS, OPEN_ARTIFACT_READ, READ_ARTIFACT_CHUNK, CLOSE_ARTIFACT_READ, LIST_PUBLICATIONS, OPEN_PUBLICATION_READ

DATA is a revision of an identity. A session or snapshot belongs to the program run that opened it. A database write ends with a final status; a durable save of a document adds an exact confirmation that the program acknowledges. Neither is durable merely because a button was pressed. See Database & Data Intents.

A snapshot can be filtered by ALL, CLASS, COLLECTION, REFERENCES, and PROPERTY_EQUALS. The typed values a database can hold include Boolean, integer, decimal/money/percentage, text/bytes, date/time/date-time/duration, enum/quantity, resource/reference/Works link, and a bounded multiple value.

Program faces

A d/BASIC program can be a console program, a window program, or both; d/OS calls these the program's two faces. The compiler works out which from the shape of the source:

Source shape Derived face
no window lifecycle or input handlers console
window handlers, no top-level executable statements windowed
top-level executable statements and window handlers console + windowed; launch surface selects

Both kinds share the same procedures, objects, arrays, imports, and one compiled program file, .dbc. A console program runs its top-level statements in order; a window program runs whenever the system calls one of its lifecycle or event handlers. See Console, Scripts & GUI.

Records

TYPE Name
  NumericField% | NumericField AS NumericType
  FixedText AS STRING * n
  Nested AS OtherRecordType
END TYPE

Access a field as record.Field. Assigning a record copies it. A record's fields can hold only numbers, fixed-width strings and other records, and a record cannot contain itself: array, variable-length STRING, CLASS, resource handle, and WEAK fields are not permitted. Arrays of records are fine.

Classes

CLASS Name [EXTENDS Base]
  [PUBLIC: | PROTECTED: | PRIVATE:]
  [STATIC] Field% | [STATIC] Field AS Type
  WEAK ObjectField AS SomeClass
  DECLARE SUB Method (...) [VIRTUAL | ABSTRACT | OVERRIDE]
  DECLARE FUNCTION Method (...) [AS Type] [VIRTUAL | ABSTRACT | OVERRIDE]
  DECLARE CONSTRUCTOR (...)
  DECLARE DESTRUCTOR
  DECLARE PROPERTY Name (...) [AS Type]
END CLASS

Bodies:

SUB ClassName.Method (...) ... END SUB
FUNCTION ClassName.Method (...) [AS Type] ... END FUNCTION
CONSTRUCTOR ClassName (...) ... END CONSTRUCTOR
DESTRUCTOR ClassName ... END DESTRUCTOR
PROPERTY ClassName.Name (...) [AS Type] ... END PROPERTY

Object expressions:

Form Meaning
NEW ClassName(arguments) construct object
NOTHING empty object reference
THIS current member receiver
A IS B same object identity
TYPEOF(A) IS ClassName class-shape test

BASE(arguments) is a statement used inside a constructor to call the chosen base-class constructor; it is not an expression.

A class field may hold a number, a variable-length STRING, an inline TYPE record, or a strong or weak object reference. Arrays and handles to host resources cannot be class fields. WEAK applies only to a field of an object and cannot be combined with STATIC.

The everyday forms are Object.Field, Object.Method(arguments), Object.Property or Object.Property(index), and ClassName.StaticField.

Window faces

A window program is written as a set of handlers that the system calls. The table lists each one and its signature:

Face Signature
open WINDOW SUB OPEN()
draw WINDOW SUB DRAW()
resize WINDOW SUB RESIZE(W AS INTEGER, H AS INTEGER)
close WINDOW SUB CLOSE()
active WINDOW SUB ACTIVE(State AS INTEGER)
visible WINDOW SUB VISIBLE(State AS INTEGER)
suspended WINDOW SUB SUSPENDED(State AS INTEGER)
minimized WINDOW SUB MINIMIZED(State AS INTEGER)
maximized WINDOW SUB MAXIMIZED(State AS INTEGER)
key ON KEY SUB (K AS INTEGER)
pointer ON POINTER SUB (X AS INTEGER, Y AS INTEGER, Buttons AS INTEGER)
menu command ON MENU SUB (ID AS INTEGER)
unified event IMPORT WIDGETS plus ON EVENT SUB (E AS UIEVENT)
accepted drop types WINDOW ACCEPTS "DOBJ", "STYL", "TEXT"
drop ON DROP SUB (D AS DROPITEM)

Every window program has exactly one OPEN, one DRAW, and one CLOSE. The other handlers are optional, and each may appear once.

ON EVENT cannot be combined with ON KEY, ON POINTER, or ON MENU; the lifecycle handlers still sit alongside it. A key event reports the state of a key; it never inserts text. TextCommit is the event that inserts text.

Start a drag with DRAG value. A TYPE or CLASS value travels as a DOBJ, the typed object a program hands to another program when you drag, drop, copy or paste, using the mapping defined for that type. See Drag, Drop & DOBJ.

DROPITEM fields:

Field Value
KIND$ accepted TEXT, STYL, PATH, FILE, or DOBJ tag
TEXT$ complete accepted plain text
PATH$ governed path/reference
HANDLE opaque callback-scoped lease for a typed structured/binary reader

Outward calls

INTENT DOMAIN.OP(arguments)
SERVICE ROW(arguments)

INTENT sends an intent, a named request such as "fill this rectangle" or "play this tone" that the machine carries out however it can. SERVICE calls one of the system's own services, such as setting the window title. The compiler checks each name, its number of arguments and their types against the official lists of intents and services. See Intents & Services.

Common window calls:

SERVICE SET_TITLE("Title")
SERVICE INVALIDATE()

INTENT GFX.BEGIN_FRAME()
INTENT GFX.SET_CLIP(X, Y, W, H)
INTENT GFX.FILL_RECT(X, Y, W, H, Color)
INTENT GFX.DRAW_TEXT(X, Y, Text$, Font, Foreground, Background)
INTENT GFX.RESET_CLIP()
INTENT GFX.PRESENT()

Application contract

APP "NAME"
  LABEL "Human label"
  ICON 24 "icon24.dic"
  ICON 16 "icon16.dic"
  NEEDS GFX, FILES, DATA, NETWORK, SOUND
END APP

NEEDS lists the capabilities the program requires, and they are checked before it starts. If the machine lacks one, or cannot run the program as the console or window program it needs to be, the launcher declines to start it and says why, rather than presenting a half-working application.

Resources and audio

Surface Purpose
LOADRESOURCE runner operation used by an owning d/Works adapter to resolve a validated package identity
GFX.BLIT_RESOURCE draw a bounded caller-array raster; distinct from a packaged asset
AUDIO.QUERY_CAPS discover voices, waveforms, rates, latency, and limits
AUDIO.NOTE_ON, NOTE_OFF start/replace or stop an app-scoped tone voice
AUDIO.PROGRAM, VOLUME, SILENCE control app-scoped tone presentation
AUDIO.PCM_OPEN, WRITE, START, STOP, CLOSE, STATS run an exact-rate PCM stream lifecycle

See Resources, Images & Sound.

Gaming & GX

IMPORT gx
Group Currently admitted GX core surface
scene GXSceneOpen, GXSceneAdvance, GXSceneReady, GXCarrierWords
entities GXEntityCapacity, GXEntityValid, GXEntitySpawn, GXEntityVelocity, GXEntityStep, GXEntityX, GXEntityY
collision GXRectOverlap, GXEntitiesOverlap
tiles GXTileIndex, GXTileSet, GXTileAt
camera GXCameraFollow, GXCameraX, GXCameraY
animation GXAnimationFrame

GX is d/BASIC's library for 2D games: scenes, sprites, tilemaps, cameras, collision. The part supported today works on one-dimensional INTEGER arrays that your program owns: eight words for a scene, ten words per entity, one word per tile, and two words for a camera. The complete engine also covers rendering, input, resources, and audio through portable intents. See Gaming & GX, the exact engine reference, and GX on 6502.

Networking

These procedures come from the dworks.network library:

Surface Purpose
WorksHttpGetText URL$, Max&, Text$, Reply bounded complete text fetch
WorksHttpGet URL$, Body%(), Reply bounded complete binary fetch
WorksNetworkCapabilities(Caps) query independent provider capabilities
WorksWifiStatus(Status), WorksWifiScan(Results) inspect system-owned Wi-Fi state
WorksSessionOpen, WorksSessionPoll begin and advance an owning session adapter
WorksSessionRead(Session, Chunk%(), Count&, EndOfStream%) partial read with EOF reported separately
WorksSessionWrite(Session, Chunk%(), Offered&, Written&) partial write with explicit offered and consumed counts
WorksSessionResize, WorksSessionDecideHostKey terminal resize and explicit SSH trust decision
WorksSessionCancel, WorksSessionClose cancel and idempotently release a session

See Networking.

Imports

IMPORT dotted.module
IMPORT dotted.module BAKED
IMPORT dotted.module SHARED

IMPORT takes a line of its own. BAKED, which copies the library's source into your program, is the default for every module, including the protected dworks.* modules and gx. Write SHARED when the program must bind to an exact installed shared library file, .dbl. See Imports & Libraries.

Intrinsics A–Z

The built-in functions, in alphabetical order:

Function Arguments Result / purpose
ABS 1 absolute numeric value
ASC 1 character code of first byte
ATN 1 arctangent
CDBL 1 convert to DOUBLE
CHR$ 1 one-character string from code
CINT 1 convert to INTEGER, nearest-even
CLNG 1 convert to LONG, nearest-even
COS 1 cosine
CSNG 1 convert to SINGLE
ERL 0 current numbered source line
ERR 0 current error/refusal number
EXP 1 exponential
FIX 1 truncate toward zero
INKEY$ 0 pending console key or empty string
INSTR 2–3 position of substring, optional start
INT 1 floor toward negative infinity
LBOUND 1–2 array lower bound, optional dimension
LCASE$ 1 lowercase ASCII text
LEFT$ 2 left substring
LEN 1 string byte length or packed TYPE record byte length
LOG 1 natural logarithm
LTRIM$ 1 remove leading ASCII whitespace
MID$ 2–3 middle substring, optional length
RIGHT$ 2 right substring
RND 0–1 next value; zero repeats; negative reseeds
RTRIM$ 1 remove trailing ASCII whitespace
SGN 1 -1, 0, or 1 by numeric sign
SIN 1 sine
SPACE$ 1 string containing spaces
SQR 1 square root
STR$ 1 canonical numeric-to-text conversion
STRING$ 2 repeated character/string construction
TAN 1 tangent
TIMER 0 canonical timer seconds
UBOUND 1–2 array upper bound, optional dimension
UCASE$ 1 uppercase ASCII text
VAL 1 canonical text-to-number conversion

TAB(n) and SPC(n) can appear only inside PRINT; they are not general functions.

Operators

From lowest precedence (evaluated last) to highest (evaluated first):

IMP
EQV
XOR
OR
AND
NOT
=  <>  ><  <  <=  >  >=  IS
+  -
MOD
\
*  /
unary +  unary -
^              (right-associative)

Punctuation also used by the grammar: ( ) , ; . @ and +=.

Normalized key values

The values a key handler receives for keys that are not printable characters, the same on every machine:

Key Value
Backspace 8
Tab 9
Enter 13
Escape 27
Delete 127
Insert 256
Arrow Up 257
Arrow Down 258
Arrow Left 259
Arrow Right 260
Home 261
End 262
Page Up 263
Page Down 264
function key Fn 0x0120 + n

Printable ASCII keys use their ASCII values.

d/Works widget entry points

The widget toolkit of d/Works, the office suite being written in d/BASIC (d/Write, d/Calc, d/Present), comes in with one import:

IMPORT dworks.widgets BAKED
Group Types
policy WorksTheme, WorksMetrics
coordination WorksSurfaceDamage, WorksLocalEvent
base/display WorksWidget, WorksPanel, WorksLabel
controls WorksButton, WorksTextField, WorksToggle, WorksIconButton, WorksTooltip
commands WorksPopoverFrame, WorksCommandRow, WorksMenuItem, WorksMenu, WorksMenuCascade, WorksStatusStrip

See the dedicated Widgets chapter for ownership, events, focus, the text caret, repainting, and menus.

Deliberate machine and object boundary

The compiler recognizes PEEK, POKE, WAIT, USR, SYS, VARPTR, DEF SEG, raw pointers, address-of, and pointer arithmetic, and declines each one with a message saying so: a d/BASIC program never touches memory addresses directly. Use values, records, objects, handles, services, and intents instead.

The same goes for objects: raw pointers to objects, DELETE, copy constructors, and OPERATOR LET are permanently not part of the language. INTERFACE / IMPLEMENTS, general operator overloading, and checked downcasts are not among d/BASIC's promises today. Prefer inheritance, virtual methods, properties, TYPEOF, and IS.

Where to look next