.topic lang.datatypes
.title Data Types
.toc 0 Data Types
.default
.index Data Types
.index Integer
.index Long
.index Single
.index Double
.index String
.index Boolean

.h1 Data Types

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

.h2 Primary Types

.table
  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)
.endtable

.h2 Internal Types

These types are not directly declarable but are used internally by the runtime.

.table
  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)
.endtable

.h2 Type Suffixes

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

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

.h2 Numeric Literals

.table
  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
.endtable

.h2 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$).

.link lang.func.conversion See also: Conversion Functions

.topic lang.operators
.title Operators
.toc 1 Operators
.index Operators
.index Precedence
.index AND
.index OR
.index NOT
.index XOR
.index EQV
.index IMP
.index MOD

.h1 Operators

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

.table
  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
.endtable

.h2 String Concatenation

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

.code
result$ = "Hello" & " " & "World"
result$ = firstName$ & " " & lastName$
.endcode

.topic lang.statements
.title Statements Overview
.toc 1 Statements
.index Statements
.index REM
.index Comments

.h1 Statements

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

.link lang.declarations Declaration Statements (DIM, REDIM, CONST, TYPE)
.link lang.conditionals Conditional Statements (IF, SELECT CASE)
.link lang.loops Loop Statements (FOR, DO, WHILE)
.link lang.procedures Procedures (SUB, FUNCTION, DEF FN)
.link lang.flow Flow Control (EXIT, CALL, GOTO, GOSUB, ON)
.link lang.io Input/Output (PRINT, INPUT, DATA/READ)
.link lang.misc Miscellaneous Statements

.topic lang.declarations
.title Declaration Statements
.toc 2 Declarations
.index DIM
.index REDIM
.index CONST
.index TYPE
.index END TYPE
.index DECLARE
.index DECLARE LIBRARY
.index SHARED
.index STATIC
.index OPTION
.index OPTION BASE
.index OPTION COMPARE
.index OPTION EXPLICIT
.index DEFINT
.index DEFLNG
.index DEFSNG
.index DEFDBL
.index DEFSTR
.index LET
.index SWAP
.index ERASE

.h1 Declaration Statements

.h2 DIM

Declares variables and arrays with an explicit type.

.code
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
.endcode

Examples:

.code
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
.endcode

.note info
DIM SHARED makes a variable accessible from all procedures without passing it as a parameter.
.endnote

.h2 REDIM

Reallocates a dynamic array, optionally preserving existing data.

.code
REDIM array(newBounds) AS type
REDIM PRESERVE array(newBounds) AS type
.endcode

.code
ReDim items(newSize) As String
ReDim Preserve scores(1 To newCount) As Integer
.endcode

.h2 CONST

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

.code
CONST name = value
.endcode

.code
Const MAX_SIZE = 100
Const PI = 3.14159265
Const APP_NAME = "DVX App"
Const DEBUG_MODE = True
.endcode

.h2 TYPE...END TYPE

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

.code
TYPE TypeName
    fieldName AS type
    ...
END TYPE
.endcode

.code
Type PersonType
    firstName As String
    lastName  As String
    age       As Integer
End Type

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

UDT fields can themselves be UDTs (nested types).

.h2 DECLARE

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

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

.h2 DECLARE LIBRARY

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

.code
DECLARE LIBRARY "libraryName"
    DECLARE SUB name ([BYVAL] param AS type, ...)
    DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType
END DECLARE
.endcode

.code
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
.endcode

.h2 STATIC

Declares a local variable that retains its value between calls.

.code
STATIC variable AS type
.endcode

.code
Sub Counter()
    Static count As Integer
    count = count + 1
    Print count
End Sub
.endcode

.h2 OPTION

Sets compiler options. Must appear before any executable code.

.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
.endcode

.h2 DEFtype Statements

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

.code
DEFINT letterRange
DEFLNG letterRange
DEFSNG letterRange
DEFDBL letterRange
DEFSTR letterRange
.endcode

.code
DefInt I-N     ' Variables starting with I through N default to Integer
DefStr S       ' Variables starting with S default to String
.endcode

.h2 Assignment

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

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

The LET keyword is optional and supported for compatibility.

.h2 SWAP

Exchanges the values of two variables.

.code
SWAP variable1, variable2
.endcode

.code
Swap a, b
.endcode

.h2 ERASE

Frees the memory of an array and resets it.

.code
ERASE arrayName
.endcode

.topic lang.conditionals
.title Conditional Statements
.toc 2 Conditionals
.index IF
.index THEN
.index ELSE
.index ELSEIF
.index END IF
.index SELECT CASE
.index CASE
.index CASE ELSE
.index END SELECT

.h1 Conditional Statements

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

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

.h3 Single-line form

.code
IF condition THEN statement
IF condition THEN statement ELSE statement
.endcode

.h3 Multi-line form

.code
IF condition THEN
    statements
ELSEIF condition THEN
    statements
ELSE
    statements
END IF
.endcode

.code
If x > 10 Then
    Print "Large"
ElseIf x > 5 Then
    Print "Medium"
Else
    Print "Small"
End If

If ready Then Print "Go!"
.endcode

.h2 SELECT CASE

Multi-way branch based on an expression value.

.code
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
.endcode

.code
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
.endcode

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

.topic lang.loops
.title Loop Statements
.toc 2 Loops
.index FOR
.index NEXT
.index STEP
.index DO
.index LOOP
.index WHILE
.index WEND
.index UNTIL
.index EXIT FOR
.index EXIT DO

.h1 Loop Statements

.h2 FOR...NEXT

Counted loop with an optional step value.

.code
FOR variable = start TO limit [STEP step]
    statements
NEXT [variable]
.endcode

.code
For i = 1 To 10
    Print i
Next i

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

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

.h2 DO...LOOP

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

.code
DO [WHILE condition | UNTIL condition]
    statements
LOOP [WHILE condition | UNTIL condition]
.endcode

.code
' 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
.endcode

.h2 WHILE...WEND

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

.code
WHILE condition
    statements
WEND
.endcode

.code
While Not EOF(1)
    Line Input #1, line$
    Print line$
Wend
.endcode

.topic lang.procedures
.title Procedures
.toc 2 Procedures
.index SUB
.index END SUB
.index FUNCTION
.index END FUNCTION
.index DEF FN
.index BYVAL
.index BYREF
.index EXIT SUB
.index EXIT FUNCTION

.h1 Procedures

.h2 SUB...END SUB

Defines a subroutine (no return value).

.code
SUB name ([BYVAL] param AS type, ...)
    statements
END SUB
.endcode

.code
Sub Greet(ByVal name As String)
    Print "Hello, " & name
End Sub
.endcode

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

.h2 FUNCTION...END FUNCTION

Defines a function with a return value.

.code
FUNCTION name ([BYVAL] param AS type, ...) AS returnType
    statements
    name = returnValue
END FUNCTION
.endcode

.code
Function Square(ByVal n As Double) As Double
    Square = n * n
End Function
.endcode

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

.h2 DEF FN

Defines a single-expression function.

.code
DEF FNname(params) = expression
.endcode

.code
Def FnSquare(x) = x * x
Print FnSquare(5)     ' prints 25
.endcode

.topic lang.flow
.title Flow Control
.toc 2 Flow Control
.index EXIT
.index CALL
.index GOTO
.index GOSUB
.index RETURN
.index ON GOTO
.index ON GOSUB

.h1 Flow Control

.h2 EXIT

Exits the current block early.

.code
EXIT FOR
EXIT DO
EXIT SUB
EXIT FUNCTION
.endcode

.h2 CALL

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

.code
CALL name
CALL name(args)
.endcode

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

.h2 GOTO / GOSUB / RETURN

.code
GOTO label
GOSUB label
RETURN
.endcode

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.

.code
GoSub Initialize
Print "Done"
End

Initialize:
    count = 0
    name$ = ""
Return
.endcode

.h2 ON...GOTO / ON...GOSUB

Computed branch based on an integer expression.

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

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.

.topic lang.io
.title Input/Output Statements
.toc 2 Input/Output
.index PRINT
.index INPUT
.index DATA
.index READ
.index RESTORE
.index SPC
.index TAB
.index PRINT USING

.h1 Input/Output Statements

.h2 PRINT

Outputs text to the console or to a file channel.

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

.list
.item ; between items -- no separator (items are concatenated)
.item , between items -- advance to the next 14-column tab zone
.item Trailing ; or , suppresses the newline
.item ? is an alias for PRINT
.endlist

Special functions inside PRINT:

.list
.item SPC(n) -- print n spaces
.item TAB(n) -- advance to column n
.endlist

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

.h2 INPUT

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

.code
INPUT variable
INPUT "prompt"; variable
INPUT #channel, variable
.endcode

.code
Input "Enter your name: "; name$
Input #1, line$
.endcode

.h2 DATA / READ / RESTORE

Inline data pool for constants.

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

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.

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

.topic lang.misc
.title Miscellaneous Statements
.toc 2 Miscellaneous Statements
.index ON ERROR
.index RESUME
.index RESUME NEXT
.index ERROR
.index ERR
.index SHELL
.index SLEEP
.index RANDOMIZE
.index END
.index RANDOMIZE TIMER

.h1 Miscellaneous Statements

.h2 Error Handling

.code
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
.endcode

The ERR keyword returns the current error number in expressions.

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

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

.h2 SHELL

Executes an operating system command.

.code
SHELL "command"
.endcode

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

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

.h2 SLEEP

Pauses execution for a specified number of seconds.

.code
SLEEP seconds
.endcode

.h2 RANDOMIZE

Seeds the random number generator.

.code
RANDOMIZE seed
RANDOMIZE TIMER          ' Seed from system clock
.endcode

.h2 END

Terminates program execution immediately.

.code
END
.endcode

.topic lang.fileio
.title File I/O
.toc 1 File I/O
.index OPEN
.index CLOSE
.index PRINT #
.index INPUT #
.index LINE INPUT
.index WRITE #
.index GET
.index PUT
.index SEEK
.index FOR INPUT
.index FOR OUTPUT
.index FOR APPEND
.index FOR RANDOM
.index FOR BINARY

.h1 File I/O

.h2 OPEN

Opens a file for reading, writing, or appending.

.code
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
.endcode

.table
  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.
.endtable

.h2 CLOSE

Closes an open file channel.

.code
CLOSE #channel
.endcode

.h2 PRINT #

Writes text to a file.

.code
PRINT #channel, expression
.endcode

.h2 INPUT #

Reads comma-delimited data from a file.

.code
INPUT #channel, variable
.endcode

.h2 LINE INPUT #

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

.code
LINE INPUT #channel, variable$
.endcode

.h2 WRITE #

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

.code
WRITE #channel, expr1, expr2, ...
.endcode

.code
Write #1, "Scott", 42, 3.14
' Output: "Scott",42,3.14
.endcode

.h2 GET / PUT

Read and write records in RANDOM or BINARY mode files.

.code
GET #channel, [recordNum], variable
PUT #channel, [recordNum], variable
.endcode

.h2 SEEK

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

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

.topic lang.func.string
.title String Functions
.toc 1 Built-in Functions
.toc 2 String Functions
.index ASC
.index CHR$
.index FORMAT$
.index HEX$
.index INSTR
.index LCASE$
.index LEFT$
.index LEN
.index LTRIM$
.index MID$
.index RIGHT$
.index RTRIM$
.index SPACE$
.index STR$
.index STRING$
.index TRIM$
.index UCASE$
.index VAL

.h1 String Functions

.table
  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
.endtable

.h2 MID$ Assignment

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

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

.topic lang.func.math
.title Math Functions
.toc 2 Math Functions
.index ABS
.index ATN
.index COS
.index EXP
.index FIX
.index INT
.index LOG
.index RND
.index SGN
.index SIN
.index SQR
.index TAN
.index TIMER

.h1 Math Functions

.table
  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
.endtable

.note info
RND with a negative argument seeds and returns. RND(0) returns the previous value. Use RANDOMIZE to seed the generator.
.endnote

.topic lang.func.conversion
.title Conversion Functions
.toc 2 Conversion Functions
.index CDBL
.index CINT
.index CLNG
.index CSNG
.index CSTR

.h1 Conversion Functions

.table
  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
.endtable

.topic lang.func.fileio
.title File I/O Functions
.toc 2 File I/O Functions
.index EOF
.index FREEFILE
.index INPUT$
.index LOC
.index LOF
.index LBOUND
.index UBOUND

.h1 File I/O Functions

.table
  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
.endtable

.topic lang.func.misc
.title Miscellaneous Functions
.toc 2 Miscellaneous Functions
.index DATE$
.index TIME$
.index ENVIRON$

.h1 Miscellaneous Functions

.table
  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)
.endtable

.topic lang.forms
.title Form and Control Statements
.toc 1 Form and Control Statements
.index LOAD
.index UNLOAD
.index Show
.index Hide
.index Me
.index DoEvents
.index DOEVENTS
.index MsgBox
.index MSGBOX
.index InputBox$
.index INPUTBOX$
.index vbModal
.index Control Arrays
.index Event Handlers

.h1 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.

.h2 Loading and Unloading Forms

.code
LOAD FormName
UNLOAD FormName
.endcode

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

.h2 Showing and Hiding Forms

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

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

.code
Form2.Show vbModal
Me.Hide
.endcode

.h2 Property Access

Read and write control properties using dot notation:

.code
ControlName.Property = value
value = ControlName.Property
.endcode

.code
Text1.Text = "Hello"
label1.Caption = "Name: " & name$
x = Text1.Left
.endcode

.h2 Method Calls

.code
ControlName.Method [args]
.endcode

.code
List1.AddItem "New entry"
List1.Clear
.endcode

.h2 Me Keyword

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

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

.h2 Control Arrays

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

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

.h2 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.

.code
DOEVENTS
.endcode

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

.h2 MsgBox

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

.code
MSGBOX message$ [, flags]
result = MSGBOX(message$ [, flags])
.endcode

.code
MsgBox "Operation complete"
answer = MsgBox("Continue?", vbYesNo + vbQuestion)
If answer = vbYes Then
    ' proceed
End If
.endcode

.h2 InputBox$

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

.code
result$ = INPUTBOX$(prompt$ [, title$ [, default$]])
.endcode

.code
name$ = InputBox$("Enter your name:", "Name Entry", "")
.endcode

.h2 Event Handler Convention

Event handlers are named ControlName_EventName and defined as SUBs:

.code
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
.endcode

.h3 Common Events

.table
  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
.endtable

.topic lang.sql
.title SQL Functions
.toc 1 SQL Functions
.index SQLOpen
.index SQLClose
.index SQLExec
.index SQLAffected
.index SQLQuery
.index SQLNext
.index SQLEof
.index SQLField$
.index SQLFieldInt
.index SQLFieldDbl
.index SQLFieldCount
.index SQLFreeResult
.index SQLError$
.index SQLite

.h1 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.

.h2 Opening and Closing Databases

.h3 SQLOpen

Opens a SQLite database file and returns a database handle.

.code
db = SQLOPEN(path$)
.endcode

.code
db = SQLOpen(App.Data & "\mydata.db")
.endcode

.h3 SQLClose

Closes an open database.

.code
SQLCLOSE db
.endcode

.h2 Executing SQL

.h3 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.

.code
SQLEXEC db, sql$
ok = SQLEXEC(db, sql$)
.endcode

.code
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")
.endcode

.h3 SQLAffected

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

.code
count = SQLAFFECTED(db)
.endcode

.h2 Querying Data

.h3 SQLQuery

Executes a SELECT query and returns a result set handle.

.code
rs = SQLQUERY(db, sql$)
.endcode

.code
rs = SQLQuery(db, "SELECT id, name FROM users ORDER BY name")
.endcode

.h3 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.

.code
SQLNEXT rs
hasRow = SQLNEXT(rs)
.endcode

.h3 SQLEof

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

.code
done = SQLEOF(rs)
.endcode

.h2 Reading Fields

.h3 SQLField$

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

.code
value$ = SQLFIELD$(rs, columnIndex)
value$ = SQLFIELD$(rs, "columnName")
.endcode

.code
name$ = SQLField$(rs, "name")
first$ = SQLField$(rs, 0)
.endcode

.h3 SQLFieldInt

Returns a field value as an integer.

.code
value = SQLFIELDINT(rs, columnIndex)
.endcode

.h3 SQLFieldDbl

Returns a field value as a double.

.code
value# = SQLFIELDDBL(rs, columnIndex)
.endcode

.h3 SQLFieldCount

Returns the number of columns in the result set.

.code
count = SQLFIELDCOUNT(rs)
.endcode

.h2 Result Set Cleanup

.h3 SQLFreeResult

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

.code
SQLFREERESULT rs
.endcode

.h2 Error Information

.h3 SQLError$

Returns the last error message for the database.

.code
msg$ = SQLERROR$(db)
.endcode

.h2 Complete SQL Example

.code
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
.endcode

.topic lang.app
.title App Object
.toc 1 App Object
.index App
.index App.Path
.index App.Config
.index App.Data

.h1 App Object

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

.table
  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.)
.endtable

.code
configFile$ = App.Config & "\settings.ini"
dbPath$ = App.Data & "\myapp.db"
Print "Running from: " & App.Path
.endcode

.topic lang.ini
.title INI Functions
.toc 1 INI Functions
.index IniRead
.index IniWrite
.index INI

.h1 INI Functions

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

.h2 IniRead

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

.code
value$ = INIREAD(file$, section$, key$, default$)
.endcode

.code
name$ = IniRead(App.Config & "\app.ini", "User", "Name", "Unknown")
fontSize = Val(IniRead(App.Config & "\app.ini", "Display", "FontSize", "12"))
.endcode

.h2 IniWrite

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

.code
INIWRITE file$, section$, key$, value$
.endcode

.code
IniWrite App.Config & "\app.ini", "User", "Name", "Scott"
IniWrite App.Config & "\app.ini", "Display", "FontSize", Str$(fontSize)
.endcode

.topic lang.constants
.title Predefined Constants
.toc 1 Predefined Constants
.index vbOKOnly
.index vbOKCancel
.index vbYesNo
.index vbYesNoCancel
.index vbRetryCancel
.index vbInformation
.index vbExclamation
.index vbCritical
.index vbQuestion
.index vbOK
.index vbCancel
.index vbYes
.index vbNo
.index vbRetry
.index True
.index False
.index Predefined Constants

.h1 Predefined Constants

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

.h2 MsgBox Button Style Flags

.table
  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
.endtable

.h2 MsgBox Icon Flags

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

.table
  Constant        Value   Description
  --------        -----   -----------
  vbInformation   &H10    Information icon
  vbExclamation   &H20    Warning icon
  vbCritical      &H30    Error/critical icon
  vbQuestion      &H40    Question mark icon
.endtable

.h2 MsgBox Return Values

.table
  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
.endtable

.h2 Show Mode Flags

.table
  Constant   Value   Description
  --------   -----   -----------
  vbModal    1       Show form as modal dialog
.endtable

.h2 Boolean Constants

.table
  Constant   Value   Description
  --------   -----   -----------
  True       -1      Boolean true
  False      0       Boolean false
.endtable
