DVX BASIC Language Reference

Complete reference for the DVX BASIC language as implemented in the DVX BASIC compiler and runtime. DVX BASIC is a QuickBASIC/Visual Basic compatible dialect targeting the DVX GUI environment.

Table of Contents

1. Data Types

DVX BASIC supports the following data types. Each type has a corresponding type suffix character that can be appended to variable names.

Type Size Suffix Range / Description
Integer 2 bytes % -32768 to 32767
Long 4 bytes & -2147483648 to 2147483647
Single 4 bytes ! 32-bit float, approximately 7 digits precision
Double 8 bytes # 64-bit float, approximately 15 digits precision
String variable $ Variable-length, reference-counted, dynamic string
Boolean 2 bytes True (-1) or False (0)

Internal Types (not directly declarable)

Internal Type Description
Array Reference-counted multi-dimensional array (up to 8 dimensions)
UDT User-defined type instance (created with TYPE...END TYPE)
Object Opaque host object (form reference, control reference)
Ref ByRef pointer to a variable slot (used for ByRef parameters)

Type Suffixes

Type suffixes can be appended to variable names to declare their type implicitly:

count%  = 42         ' Integer
total&  = 100000     ' Long
rate!   = 3.14       ' Single
pi#     = 3.14159265 ' Double
name$   = "Hello"    ' String

Numeric Literals

FormExampleDescription
Decimal integer42Values -32768..32767 are Integer; larger values are Long
Hex integer&HFFHexadecimal literal
Long suffix42&, &HFF&Force Long type
Floating-point3.14, 1.5E10Double by default
Single suffix3.14!Force Single type
Double suffix3.14#Force Double type

Type Promotion

When mixing types in expressions, values are automatically promoted to a common type: Integer -> Long -> Single -> Double. Strings are not automatically converted to numbers (use VAL and STR$).

2. Operators

Operators listed from highest precedence (evaluated first) to lowest precedence (evaluated last).

Precedence Operator Description
1 (highest) ^ Exponentiation
2 - (unary) Negation
3 *   /   \   MOD Multiplication, float division, integer division, modulus
4 +   - Addition, subtraction
5 & String concatenation
6 =   <>   <   >   <=   >= Comparison (returns Boolean)
7 NOT Logical/bitwise NOT
8 AND Logical/bitwise AND
9 XOR Logical/bitwise XOR
10 OR Logical/bitwise OR
11 EQV Logical/bitwise equivalence
12 (lowest) IMP Logical/bitwise implication

String Concatenation

Use & to concatenate strings. The + operator also concatenates when both operands are strings.

result$ = "Hello" & " " & "World"
result$ = firstName$ & " " & lastName$

3. Statements

Multiple statements can appear on one line separated by :. Lines can be continued with _ at the end. Comments start with ' or REM.

DIM

Declares variables and arrays with an explicit type.

DIM variable AS type
DIM variable(upperBound) AS type
DIM variable(lower TO upper) AS type
DIM variable(dim1, dim2, ...) AS type
DIM variable AS UdtName
DIM variable AS STRING * n
DIM SHARED variable AS type

Examples:

Dim name As String
Dim count As Integer
Dim values(100) As Double
Dim matrix(1 To 10, 1 To 10) As Single
Dim Shared globalFlag As Boolean
Dim record As PersonType
Dim fixedStr As String * 20
DIM SHARED makes a variable accessible from all procedures without passing it as a parameter.

REDIM

Reallocates a dynamic array, optionally preserving existing data.

REDIM array(newBounds) AS type
REDIM PRESERVE array(newBounds) AS type
ReDim items(newSize) As String
ReDim Preserve scores(1 To newCount) As Integer

CONST

Declares a named constant. The value must be a literal (integer, float, string, or boolean).

CONST name = value
Const MAX_SIZE = 100
Const PI = 3.14159265
Const APP_NAME = "DVX App"
Const DEBUG_MODE = True

TYPE...END TYPE

Defines a user-defined type (record/structure).

TYPE TypeName
    fieldName AS type
    ...
END TYPE
Type PersonType
    firstName As String
    lastName  As String
    age       As Integer
End Type

Dim p As PersonType
p.firstName = "Scott"
p.age = 30

UDT fields can themselves be UDTs (nested types).

IF...THEN...ELSE...END IF

Conditional execution. Supports single-line and multi-line forms.

Single-line form:

IF condition THEN statement
IF condition THEN statement ELSE statement

Multi-line form:

IF condition THEN
    statements
ELSEIF condition THEN
    statements
ELSE
    statements
END IF
If x > 10 Then
    Print "Large"
ElseIf x > 5 Then
    Print "Medium"
Else
    Print "Small"
End If

If ready Then Print "Go!"

SELECT CASE

Multi-way branch based on an expression value.

SELECT CASE expression
    CASE value
        statements
    CASE value1, value2
        statements
    CASE low TO high
        statements
    CASE IS operator value
        statements
    CASE ELSE
        statements
END SELECT
Select Case grade
    Case 90 To 100
        Print "A"
    Case 80 To 89
        Print "B"
    Case Is >= 70
        Print "C"
    Case 60, 65
        Print "D (borderline)"
    Case Else
        Print "F"
End Select

CASE items can be combined with commas. The IS keyword allows comparison operators: <, >, <=, >=, =, <>.

FOR...NEXT

Counted loop with an optional step value.

FOR variable = start TO limit [STEP step]
    statements
NEXT [variable]
For i = 1 To 10
    Print i
Next i

For x = 10 To 0 Step -2
    Print x
Next

The variable name after NEXT is optional. Use EXIT FOR to break out early.

DO...LOOP

General-purpose loop with pre-test, post-test, or infinite forms.

DO [WHILE condition | UNTIL condition]
    statements
LOOP [WHILE condition | UNTIL condition]
' Pre-test
Do While count < 10
    count = count + 1
Loop

' Post-test
Do
    line$ = ReadLine()
Loop Until line$ = "quit"

' Infinite loop (exit with EXIT DO)
Do
    DoEvents
    If done Then Exit Do
Loop

WHILE...WEND

Simple pre-test loop (legacy form; prefer DO...LOOP).

WHILE condition
    statements
WEND
While Not EOF(1)
    Line Input #1, line$
    Print line$
Wend

SUB...END SUB

Defines a subroutine (no return value).

SUB name ([BYVAL] param AS type, ...)
    statements
END SUB
Sub Greet(ByVal name As String)
    Print "Hello, " & name
End Sub

Parameters are passed ByRef by default. Use ByVal for value semantics. Use EXIT SUB to return early.

FUNCTION...END FUNCTION

Defines a function with a return value.

FUNCTION name ([BYVAL] param AS type, ...) AS returnType
    statements
    name = returnValue
END FUNCTION
Function Square(ByVal n As Double) As Double
    Square = n * n
End Function

Assign to the function name to set the return value. Use EXIT FUNCTION to return early.

DEF FN

Defines a single-expression function.

DEF FNname(params) = expression
Def FnSquare(x) = x * x
Print FnSquare(5)     ' prints 25

EXIT

Exits the current block early.

EXIT FOR
EXIT DO
EXIT SUB
EXIT FUNCTION

CALL

Explicitly calls a subroutine or function. The return value (if any) is discarded.

CALL name
CALL name(args)

Normally you can omit CALL and just use the name directly.

GOTO / GOSUB / RETURN

GOTO label
GOSUB label
RETURN

GOSUB pushes the return address, executes code at the label, and RETURN jumps back. At module level, RETURN returns from a GOSUB. Inside a SUB/FUNCTION, RETURN returns from the procedure.

GoSub Initialize
Print "Done"
End

Initialize:
    count = 0
    name$ = ""
Return

ON...GOTO / ON...GOSUB

Computed branch based on an integer expression.

ON expression GOTO label1, label2, ...
ON expression GOSUB label1, label2, ...

If the expression evaluates to 1, control goes to the first label; 2, the second; and so on. If out of range, execution falls through.

PRINT

Outputs text to the console or to a file channel.

PRINT [expression] [{; | ,} expression] ...
PRINT #channel, expression
PRINT USING format$; expression [; expression] ...

Special functions inside PRINT:

Print "Name:"; Tab(20); name$
Print Using "###.##"; total
Print #1, "Written to file"

INPUT

Reads a line of text from the user or from a file channel.

INPUT variable
INPUT "prompt"; variable
INPUT #channel, variable
Input "Enter your name: "; name$
Input #1, line$

DATA / READ / RESTORE

Inline data pool for constants.

DATA value1, value2, "string", ...
READ variable1, variable2, ...
RESTORE

DATA statements define a pool of values. READ reads the next value from the pool into a variable. RESTORE resets the read pointer to the beginning.

Data 10, 20, 30, "Hello"
Read a, b, c, msg$
Print a; b; c; msg$
Restore

Assignment

Assigns a value to a variable, array element, or UDT field.

variable = expression
array(index) = expression
udt.field = expression
LET variable = expression

The LET keyword is optional and supported for compatibility.

SWAP

Exchanges the values of two variables.

SWAP variable1, variable2
Swap a, b

ERASE

Frees the memory of an array and resets it.

ERASE arrayName

OPTION

Sets compiler options. Must appear before any executable code.

OPTION BASE 0          ' Arrays start at index 0 (default)
OPTION BASE 1          ' Arrays start at index 1
OPTION COMPARE BINARY  ' Case-sensitive string comparisons (default)
OPTION COMPARE TEXT    ' Case-insensitive string comparisons
OPTION EXPLICIT        ' All variables must be declared with DIM

DEFtype Statements

Set the default type for variables based on their first letter.

DEFINT letterRange
DEFLNG letterRange
DEFSNG letterRange
DEFDBL letterRange
DEFSTR letterRange
DefInt I-N     ' Variables starting with I through N default to Integer
DefStr S       ' Variables starting with S default to String

STATIC

Declares a local variable that retains its value between calls.

STATIC variable AS type
Sub Counter()
    Static count As Integer
    count = count + 1
    Print count
End Sub

Error Handling

ON ERROR GOTO label     ' Enable error handler
ON ERROR GOTO 0          ' Disable error handler
RESUME                   ' Retry the statement that caused the error
RESUME NEXT              ' Continue at the next statement after the error
ERROR n                  ' Raise a runtime error with error number n

The ERR keyword returns the current error number in expressions.

On Error GoTo ErrorHandler
Open "missing.txt" For Input As #1
Exit Sub

ErrorHandler:
    Print "Error number:"; Err
    Resume Next

SHELL

Executes an operating system command.

SHELL "command"

When used as a function, returns the exit code of the command.

Shell "DIR /B"
exitCode = Shell("COPY A.TXT B.TXT")

SLEEP

Pauses execution for a specified number of seconds.

SLEEP seconds

RANDOMIZE

Seeds the random number generator.

RANDOMIZE seed
RANDOMIZE TIMER          ' Seed from system clock

END

Terminates program execution immediately.

END

DECLARE

Forward-declares a SUB or FUNCTION. Required when a procedure is called before it is defined.

DECLARE SUB name ([BYVAL] param AS type, ...)
DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType

DECLARE LIBRARY

Declares external native functions from a dynamically loaded library. This allows BASIC programs to call functions exported by DXE libraries.

DECLARE LIBRARY "libraryName"
    DECLARE SUB name ([BYVAL] param AS type, ...)
    DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType
END DECLARE
Declare Library "rs232"
    Declare Function ComOpen(ByVal port As Integer) As Integer
    Declare Sub ComClose(ByVal port As Integer)
    Declare Sub ComSend(ByVal port As Integer, ByVal data$ As String)
End Declare

4. File I/O

OPEN

Opens a file for reading, writing, or appending.

OPEN filename$ FOR INPUT AS #channel
OPEN filename$ FOR OUTPUT AS #channel
OPEN filename$ FOR APPEND AS #channel
OPEN filename$ FOR RANDOM AS #channel [LEN = recordSize]
OPEN filename$ FOR BINARY AS #channel
ModeDescription
INPUTOpen for sequential reading. File must exist.
OUTPUTOpen for sequential writing. Creates or truncates.
APPENDOpen for sequential writing at end of file.
RANDOMOpen for random-access record I/O.
BINARYOpen for raw binary I/O.

CLOSE

CLOSE #channel

PRINT #

Writes text to a file.

PRINT #channel, expression

INPUT #

Reads comma-delimited data from a file.

INPUT #channel, variable

LINE INPUT #

Reads an entire line from a file into a string variable.

LINE INPUT #channel, variable$

WRITE #

Writes comma-delimited data to a file. Strings are enclosed in quotes, numbers are undecorated. Each statement writes a newline at the end.

WRITE #channel, expr1, expr2, ...
Write #1, "Scott", 42, 3.14
' Output: "Scott",42,3.14

GET / PUT

Read and write records in RANDOM or BINARY mode files.

GET #channel, [recordNum], variable
PUT #channel, [recordNum], variable

SEEK

Sets the file position. As a function, returns the current position.

SEEK #channel, position      ' Statement: set position
pos = SEEK(channel)           ' Function: get current position

5. Built-in Functions

String Functions

Function Args Returns Description
ASC(s$) 1 Integer Returns the ASCII code of the first character of s$.
CHR$(n) 1 String Returns the character with ASCII code n.
FORMAT$(value, fmt$) 2 String Formats a numeric value using the format string fmt$.
HEX$(n) 1 String Returns the hexadecimal representation of n.
INSTR(s$, find$) 2-3 Integer Returns the position of find$ in s$ (1-based). Optionally takes a starting position as the first argument: INSTR(start, s$, find$). Returns 0 if not found.
LCASE$(s$) 1 String Converts s$ to lowercase.
LEFT$(s$, n) 2 String Returns the leftmost n characters of s$.
LEN(s$) 1 Integer Returns the length of s$.
LTRIM$(s$) 1 String Removes leading spaces from s$.
MID$(s$, start [, length]) 2-3 String Returns a substring starting at position start (1-based). If length is omitted, returns from start to end.
RIGHT$(s$, n) 2 String Returns the rightmost n characters of s$.
RTRIM$(s$) 1 String Removes trailing spaces from s$.
SPACE$(n) 1 String Returns a string of n spaces.
STR$(n) 1 String Converts number n to its string representation.
STRING$(n, char) 2 String Returns a string of n copies of char (ASCII code or single-character string).
TRIM$(s$) 1 String Removes leading and trailing spaces from s$.
UCASE$(s$) 1 String Converts s$ to uppercase.
VAL(s$) 1 Double Converts the string s$ to a numeric value.

MID$ Assignment

MID$ can also be used on the left side of an assignment to replace a portion of a string:

Mid$(s$, 3, 2) = "XY"    ' Replace 2 characters starting at position 3

Math Functions

Function Args Returns Description
ABS(n) 1 Double Absolute value of n.
ATN(n) 1 Double Arctangent of n (in radians).
COS(n) 1 Double Cosine of n (radians).
EXP(n) 1 Double Returns e raised to the power n.
FIX(n) 1 Integer Truncates n toward zero (removes the fractional part).
INT(n) 1 Integer Returns the largest integer less than or equal to n (floor).
LOG(n) 1 Double Natural logarithm (base e) of n.
RND[(n)] 0-1 Double Returns a random number between 0 (inclusive) and 1 (exclusive). With a negative argument, seeds and returns. With 0, returns the previous value.
SGN(n) 1 Integer Returns the sign of n: -1, 0, or 1.
SIN(n) 1 Double Sine of n (radians).
SQR(n) 1 Double Square root of n.
TAN(n) 1 Double Tangent of n (radians).
TIMER 0 Double Returns the number of seconds since midnight.

Conversion Functions

Function Args Returns Description
CDBL(n) 1 Double Converts n to Double.
CINT(n) 1 Integer Converts n to Integer (with banker's rounding).
CLNG(n) 1 Long Converts n to Long.
CSNG(n) 1 Single Converts n to Single.
CSTR(n) 1 String Converts n to its String representation.

File I/O Functions

Function Args Returns Description
EOF(channel) 1 Boolean Returns True if the file pointer is at end of file.
FREEFILE 0 Integer Returns the next available file channel number.
INPUT$(n, #channel) 2 String Reads n characters from the file and returns them as a string.
LOC(channel) 1 Long Returns the current read/write position in the file.
LOF(channel) 1 Long Returns the length of the file in bytes.
SEEK(channel) 1 Long Returns the current file position (function form of SEEK).
LBOUND(array [, dim]) 1-2 Integer Returns the lower bound of an array dimension.
UBOUND(array [, dim]) 1-2 Integer Returns the upper bound of an array dimension.

Miscellaneous Functions

Function Args Returns Description
DATE$ 0 String Returns the current date as "MM-DD-YYYY".
TIME$ 0 String Returns the current time as "HH:MM:SS".
ENVIRON$(name$) 1 String Returns the value of the environment variable name$.
ERR 0 Integer Returns the current runtime error number (0 if no error).

6. Form and Control Statements

DVX BASIC supports Visual Basic-style forms and controls for building graphical user interfaces. Forms are defined in .frm files and loaded at runtime.

Loading and Unloading Forms

LOAD FormName
UNLOAD FormName

LOAD creates the form and its controls in memory. UNLOAD destroys the form and frees its resources.

Showing and Hiding Forms

FormName.Show [modal]
FormName.Hide
Me.Show [modal]
Me.Hide

Pass vbModal (1) to Show for a modal dialog.

Form2.Show vbModal
Me.Hide

Property Access

Read and write control properties using dot notation:

ControlName.Property = value
value = ControlName.Property
Text1.Text = "Hello"
label1.Caption = "Name: " & name$
x = Text1.Left

Method Calls

ControlName.Method [args]
List1.AddItem "New entry"
List1.Clear

Me Keyword

Me refers to the current form. Use it to access the form's own properties, controls, and methods from within event handlers.

Me.Caption = "Updated Title"
Me.Text1.Text = ""
Me.Hide

Control Arrays

Multiple controls can share a name with unique indices. Access individual controls with parenthesized indices:

Option1(0).Value = True
Label1(idx).Caption = "Item " & Str$(idx)
Me.Label1(i).Visible = True

DoEvents

Yields control to the DVX event loop, allowing the GUI to process pending events. Call this in long-running loops to keep the UI responsive.

DOEVENTS
For i = 1 To 10000
    ' process data
    If i Mod 100 = 0 Then DoEvents
Next

MsgBox

Displays a message box dialog. Can be used as a statement (discards result) or as a function (returns the button clicked).

MSGBOX message$ [, flags]
result = MSGBOX(message$ [, flags])
MsgBox "Operation complete"
answer = MsgBox("Continue?", vbYesNo + vbQuestion)
If answer = vbYes Then
    ' proceed
End If

InputBox$

Displays an input dialog and returns the user's text entry.

result$ = INPUTBOX$(prompt$ [, title$ [, default$]])
name$ = InputBox$("Enter your name:", "Name Entry", "")

Event Handler Convention

Event handlers are named ControlName_EventName and defined as SUBs:

Sub Command1_Click()
    MsgBox "Button clicked!"
End Sub

Sub Form_Load()
    Me.Caption = "My App"
End Sub

Sub Text1_Change()
    Label1.Caption = "You typed: " & Text1.Text
End Sub

Common events:

EventDescription
ClickControl was clicked
DblClickControl was double-clicked
ChangeControl value/text changed
KeyPressKey was pressed (receives key code)
KeyDownKey went down (receives key code and shift state)
KeyUpKey was released
MouseDownMouse button pressed
MouseUpMouse button released
MouseMoveMouse moved over control
GotFocusControl received input focus
LostFocusControl lost input focus
Form_LoadForm is being loaded
Form_UnloadForm is being unloaded
Form_ResizeForm was resized
TimerTimer interval elapsed

7. SQL Functions

DVX BASIC includes built-in SQLite database support through a set of SQL functions. All functions use database handles and result set handles (integers) returned by SQLOpen and SQLQuery.

Opening and Closing Databases

SQLOpen

Opens a SQLite database file and returns a database handle.

db = SQLOPEN(path$)
db = SQLOpen(App.Data & "\mydata.db")

SQLClose

Closes an open database.

SQLCLOSE db

Executing SQL

SQLExec

Executes a SQL statement that does not return data (INSERT, UPDATE, DELETE, CREATE TABLE, etc.). Can be used as a statement or as a function returning a Boolean success flag.

SQLEXEC db, sql$
ok = SQLEXEC(db, sql$)
SQLExec db, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
SQLExec db, "INSERT INTO users (name) VALUES ('Scott')"
ok = SQLExec(db, "DELETE FROM users WHERE id = 5")

SQLAffected

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE.

count = SQLAFFECTED(db)

Querying Data

SQLQuery

Executes a SELECT query and returns a result set handle.

rs = SQLQUERY(db, sql$)
rs = SQLQuery(db, "SELECT id, name FROM users ORDER BY name")

SQLNext

Advances to the next row in the result set. Can be used as a statement or as a function returning True if a row is available.

SQLNEXT rs
hasRow = SQLNEXT(rs)

SQLEof

Returns True if there are no more rows in the result set.

done = SQLEOF(rs)

Reading Fields

SQLField$

Returns a field value as a string. The field can be specified by column index (0-based) or by column name.

value$ = SQLFIELD$(rs, columnIndex)
value$ = SQLFIELD$(rs, "columnName")
name$ = SQLField$(rs, "name")
first$ = SQLField$(rs, 0)

SQLFieldInt

Returns a field value as an integer.

value = SQLFIELDINT(rs, columnIndex)

SQLFieldDbl

Returns a field value as a double.

value# = SQLFIELDDBL(rs, columnIndex)

SQLFieldCount

Returns the number of columns in the result set.

count = SQLFIELDCOUNT(rs)

Result Set Cleanup

SQLFreeResult

Frees a result set. Always call this when done iterating a query.

SQLFREERESULT rs

Error Information

SQLError$

Returns the last error message for the database.

msg$ = SQLERROR$(db)

Complete SQL Example

Dim db As Long
Dim rs As Long

db = SQLOpen(App.Data & "\contacts.db")
SQLExec db, "CREATE TABLE IF NOT EXISTS contacts (name TEXT, phone TEXT)"
SQLExec db, "INSERT INTO contacts VALUES ('Alice', '555-1234')"

rs = SQLQuery(db, "SELECT name, phone FROM contacts")
Do While Not SQLEof(rs)
    SQLNext rs
    Print SQLField$(rs, "name"); Tab(20); SQLField$(rs, "phone")
Loop
SQLFreeResult rs
SQLClose db

8. App Object

The App object provides read-only properties for the application's directory paths.

Property Returns Description
App.Path String The directory containing the application's executable.
App.Config String The directory for application configuration files.
App.Data String The directory for application data files (databases, etc.).
configFile$ = App.Config & "\settings.ini"
dbPath$ = App.Data & "\myapp.db"
Print "Running from: " & App.Path

9. INI Functions

DVX BASIC provides built-in functions for reading and writing standard INI configuration files.

IniRead

Reads a value from an INI file. Returns the default value if the key is not found.

value$ = INIREAD(file$, section$, key$, default$)
name$ = IniRead(App.Config & "\app.ini", "User", "Name", "Unknown")
fontSize = Val(IniRead(App.Config & "\app.ini", "Display", "FontSize", "12"))

IniWrite

Writes a value to an INI file. Creates the file, section, or key if they do not exist.

INIWRITE file$, section$, key$, value$
IniWrite App.Config & "\app.ini", "User", "Name", "Scott"
IniWrite App.Config & "\app.ini", "Display", "FontSize", Str$(fontSize)

10. Predefined Constants

The following constants are predefined by the compiler and available in all programs.

MsgBox Button Style Flags

ConstantValueDescription
vbOKOnly0OK button only (default)
vbOKCancel1OK and Cancel buttons
vbYesNo2Yes and No buttons
vbYesNoCancel3Yes, No, and Cancel buttons
vbRetryCancel4Retry and Cancel buttons

MsgBox Icon Flags

Add an icon flag to the button style to display an icon in the message box.

ConstantValueDescription
vbInformation&H10Information icon
vbExclamation&H20Warning icon
vbCritical&H30Error/critical icon
vbQuestion&H40Question mark icon

MsgBox Return Values

ConstantValueDescription
vbOK1User clicked OK
vbCancel2User clicked Cancel
vbYes3User clicked Yes
vbNo4User clicked No
vbRetry5User clicked Retry

Show Mode Flags

ConstantValueDescription
vbModal1Show form as modal dialog

Boolean Constants

ConstantValueDescription
True-1Boolean true
False0Boolean false

DVX BASIC Language Reference -- Generated from compiler source code. Covers the lexer, parser, and VM opcode set as implemented.