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.
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 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 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
| Form | Example | Description |
|---|---|---|
| Decimal integer | 42 | Values -32768..32767 are Integer; larger values are Long |
| Hex integer | &HFF | Hexadecimal literal |
| Long suffix | 42&, &HFF& | Force Long type |
| Floating-point | 3.14, 1.5E10 | Double by default |
| Single suffix | 3.14! | Force Single type |
| Double suffix | 3.14# | Force Double type |
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$).
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 |
Use & to concatenate strings. The + operator
also concatenates when both operands are strings.
result$ = "Hello" & " " & "World" result$ = firstName$ & " " & lastName$
Multiple statements can appear on one line separated by :.
Lines can be continued with _ at the end. Comments start with
' or REM.
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.
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
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
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).
Conditional execution. Supports single-line and multi-line forms.
IF condition THEN statement IF condition THEN statement ELSE statement
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!"
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: <, >,
<=, >=, =,
<>.
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.
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
Simple pre-test loop (legacy form; prefer DO...LOOP).
WHILE condition
statements
WEND
While Not EOF(1)
Line Input #1, line$
Print line$
Wend
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.
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.
Defines a single-expression function.
DEF FNname(params) = expression
Def FnSquare(x) = x * x Print FnSquare(5) ' prints 25
Exits the current block early.
EXIT FOR EXIT DO EXIT SUB EXIT FUNCTION
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 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
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.
Outputs text to the console or to a file channel.
PRINT [expression] [{; | ,} expression] ...
PRINT #channel, expression
PRINT USING format$; expression [; expression] ...
; between items -- no separator (items are concatenated), between items -- advance to the next 14-column tab zone; or , suppresses the newline? is an alias for PRINTSpecial functions inside PRINT:
SPC(n) -- print n spacesTAB(n) -- advance to column nPrint "Name:"; Tab(20); name$ Print Using "###.##"; total Print #1, "Written to file"
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$
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
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.
Exchanges the values of two variables.
SWAP variable1, variable2
Swap a, b
Frees the memory of an array and resets it.
ERASE arrayName
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
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
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
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
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")
Pauses execution for a specified number of seconds.
SLEEP seconds
Seeds the random number generator.
RANDOMIZE seed RANDOMIZE TIMER ' Seed from system clock
Terminates program execution immediately.
END
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
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
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
| Mode | Description |
|---|---|
INPUT | Open for sequential reading. File must exist. |
OUTPUT | Open for sequential writing. Creates or truncates. |
APPEND | Open for sequential writing at end of file. |
RANDOM | Open for random-access record I/O. |
BINARY | Open for raw binary I/O. |
CLOSE #channel
Writes text to a file.
PRINT #channel, expression
Reads comma-delimited data from a file.
INPUT #channel, variable
Reads an entire line from a file into a string variable.
LINE INPUT #channel, variable$
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
Read and write records in RANDOM or BINARY mode files.
GET #channel, [recordNum], variable PUT #channel, [recordNum], variable
Sets the file position. As a function, returns the current position.
SEEK #channel, position ' Statement: set position pos = SEEK(channel) ' Function: get current position
| 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$ 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
| 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. |
| 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. |
| 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. |
| 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). |
DVX BASIC supports Visual Basic-style forms and controls for building
graphical user interfaces. Forms are defined in .frm files and
loaded at runtime.
LOAD FormName UNLOAD FormName
LOAD creates the form and its controls in memory.
UNLOAD destroys the form and frees its resources.
FormName.Show [modal] FormName.Hide Me.Show [modal] Me.Hide
Pass vbModal (1) to Show for a modal dialog.
Form2.Show vbModal Me.Hide
Read and write control properties using dot notation:
ControlName.Property = value value = ControlName.Property
Text1.Text = "Hello" label1.Caption = "Name: " & name$ x = Text1.Left
ControlName.Method [args]
List1.AddItem "New entry" List1.Clear
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
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
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
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
Displays an input dialog and returns the user's text entry.
result$ = INPUTBOX$(prompt$ [, title$ [, default$]])
name$ = InputBox$("Enter your name:", "Name Entry", "")
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:
| Event | Description |
|---|---|
Click | Control was clicked |
DblClick | Control was double-clicked |
Change | Control value/text changed |
KeyPress | Key was pressed (receives key code) |
KeyDown | Key went down (receives key code and shift state) |
KeyUp | Key was released |
MouseDown | Mouse button pressed |
MouseUp | Mouse button released |
MouseMove | Mouse moved over control |
GotFocus | Control received input focus |
LostFocus | Control lost input focus |
Form_Load | Form is being loaded |
Form_Unload | Form is being unloaded |
Form_Resize | Form was resized |
Timer | Timer interval elapsed |
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.
Opens a SQLite database file and returns a database handle.
db = SQLOPEN(path$)
db = SQLOpen(App.Data & "\mydata.db")
Closes an open database.
SQLCLOSE db
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")
Returns the number of rows affected by the last INSERT, UPDATE, or DELETE.
count = SQLAFFECTED(db)
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")
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)
Returns True if there are no more rows in the result set.
done = SQLEOF(rs)
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)
Returns a field value as an integer.
value = SQLFIELDINT(rs, columnIndex)
Returns a field value as a double.
value# = SQLFIELDDBL(rs, columnIndex)
Returns the number of columns in the result set.
count = SQLFIELDCOUNT(rs)
Frees a result set. Always call this when done iterating a query.
SQLFREERESULT rs
Returns the last error message for the database.
msg$ = SQLERROR$(db)
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
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
DVX BASIC provides built-in functions for reading and writing standard INI configuration files.
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"))
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)
The following constants are predefined by the compiler and available in all programs.
| Constant | Value | Description |
|---|---|---|
vbOKOnly | 0 | OK button only (default) |
vbOKCancel | 1 | OK and Cancel buttons |
vbYesNo | 2 | Yes and No buttons |
vbYesNoCancel | 3 | Yes, No, and Cancel buttons |
vbRetryCancel | 4 | Retry and Cancel buttons |
Add an icon flag to the button style to display an icon in the message box.
| Constant | Value | Description |
|---|---|---|
vbInformation | &H10 | Information icon |
vbExclamation | &H20 | Warning icon |
vbCritical | &H30 | Error/critical icon |
vbQuestion | &H40 | Question mark icon |
| Constant | Value | Description |
|---|---|---|
vbOK | 1 | User clicked OK |
vbCancel | 2 | User clicked Cancel |
vbYes | 3 | User clicked Yes |
vbNo | 4 | User clicked No |
vbRetry | 5 | User clicked Retry |
| Constant | Value | Description |
|---|---|---|
vbModal | 1 | Show form as modal dialog |
| Constant | Value | Description |
|---|---|---|
True | -1 | Boolean true |
False | 0 | Boolean false |
DVX BASIC Language Reference -- Generated from compiler source code. Covers the lexer, parser, and VM opcode set as implemented.