Data Types
Data Types
DVX BASIC supports the following data types. Each type has a corresponding type suffix character that can be appended to variable names.
Primary Types
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 (none) True (-1) or False (0)
Internal Types
These types are not directly declarable but are used internally by the runtime.
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
Form Example Description ---- ------- ----------- Decimal integer 42 Values -32768..32767 are Integer; larger 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
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$).
Operators
Operators
Operators listed from highest precedence (evaluated first) to lowest precedence (evaluated last).
Precedence Operator Description ---------- -------- ----------- 1 (highest) ^ Exponentiation 2 - (unary) Negation 3 * / \ MOD Multiply, float div, integer div, 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$
Statements Overview
Statements
Multiple statements can appear on one line separated by :. Lines can be continued with _ at the end. Comments start with ' or REM.
Declaration Statements (DIM, REDIM, CONST, TYPE)
Conditional Statements (IF, SELECT CASE)
Loop Statements (FOR, DO, WHILE)
Procedures (SUB, FUNCTION, DEF FN)
Flow Control (EXIT, CALL, GOTO, GOSUB, ON)
Declaration Statements
Declaration Statements
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
Note: 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).
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
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
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
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
Conditional Statements
Conditional Statements
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: <, >, <=, >=, =, <>.
Loop Statements
Loop Statements
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
Procedures
Procedures
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
Flow Control
Flow Control
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.
Input/Output Statements
Input/Output Statements
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
- Trailing ; or , suppresses the newline
? is an alias for PRINT
Special functions inside PRINT:
- SPC(n) -- print n spaces
TAB(n) -- advance to column n
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
Miscellaneous Statements
Miscellaneous Statements
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
File I/O
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
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
Closes an open file channel.
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
String Functions
String Functions
Function Returns Description -------- ------- ----------- ASC(s$) Integer ASCII code of first character of s$ CHR$(n) String Character with ASCII code n FORMAT$(value, fmt$) String Formats a numeric value using format string HEX$(n) String Hexadecimal representation of n INSTR(s$, find$) Integer Position of find$ in s$ (1-based), 0 if not found INSTR(start, s$, find$) Integer Search starting at position start LCASE$(s$) String Converts s$ to lowercase LEFT$(s$, n) String Leftmost n characters of s$ LEN(s$) Integer Length of s$ LTRIM$(s$) String Removes leading spaces from s$ MID$(s$, start [, length]) String Substring from position start (1-based) RIGHT$(s$, n) String Rightmost n characters of s$ RTRIM$(s$) String Removes trailing spaces from s$ SPACE$(n) String String of n spaces STR$(n) String Converts number n to string STRING$(n, char) String String of n copies of char TRIM$(s$) String Removes leading and trailing spaces from s$ UCASE$(s$) String Converts s$ to uppercase VAL(s$) Double Converts 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
Math Functions
Function Returns Description -------- ------- ----------- ABS(n) Double Absolute value of n ATN(n) Double Arctangent of n (in radians) COS(n) Double Cosine of n (radians) EXP(n) Double e raised to the power n FIX(n) Integer Truncates n toward zero (removes fractional part) INT(n) Integer Largest integer less than or equal to n (floor) LOG(n) Double Natural logarithm (base e) of n RND[(n)] Double Random number between 0 (inclusive) and 1 (exclusive) SGN(n) Integer Sign of n: -1, 0, or 1 SIN(n) Double Sine of n (radians) SQR(n) Double Square root of n TAN(n) Double Tangent of n (radians) TIMER Double Number of seconds since midnight
Note: RND with a negative argument seeds and returns. RND(0) returns the previous value. Use RANDOMIZE to seed the generator.
Conversion Functions
Conversion Functions
Function Returns Description -------- ------- ----------- CDBL(n) Double Converts n to Double CINT(n) Integer Converts n to Integer (with banker's rounding) CLNG(n) Long Converts n to Long CSNG(n) Single Converts n to Single CSTR(n) String Converts n to its String representation
File I/O Functions
File I/O Functions
Function Returns Description -------- ------- ----------- EOF(channel) Boolean True if file pointer is at end of file FREEFILE Integer Next available file channel number INPUT$(n, #channel) String Reads n characters from the file LOC(channel) Long Current read/write position in the file LOF(channel) Long Length of the file in bytes SEEK(channel) Long Current file position (function form) LBOUND(array [, dim]) Integer Lower bound of an array dimension UBOUND(array [, dim]) Integer Upper bound of an array dimension
Miscellaneous Functions
Miscellaneous Functions
Function Returns Description -------- ------- ----------- DATE$ String Current date as "MM-DD-YYYY" TIME$ String Current time as "HH:MM:SS" ENVIRON$(name$) String Value of environment variable name$ ERR Integer Current runtime error number (0 if no error)
Form and Control Statements
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
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
SQL Functions
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
App Object
App Object
The App object provides read-only properties for the application's directory paths.
Property Returns Description -------- ------- ----------- App.Path String Directory containing the application's executable App.Config String Directory for application configuration files App.Data String Directory for application data files (databases, etc.)
configFile$ = App.Config & "\settings.ini"
dbPath$ = App.Data & "\myapp.db"
Print "Running from: " & App.Path
INI Functions
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)
Predefined Constants
Predefined Constants
The following constants are predefined by the compiler and available in all programs.
MsgBox Button Style Flags
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
MsgBox Icon Flags
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
MsgBox Return Values
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
Show Mode Flags
Constant Value Description -------- ----- ----------- vbModal 1 Show form as modal dialog
Boolean Constants
Constant Value Description -------- ----- ----------- True -1 Boolean true False 0 Boolean false