# The MIT License (MIT)
#
# Copyright (C) 2026 Scott Duensing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

.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, &H1234           Hexadecimal literal
  Integer suffix     42%                    Force Integer type
  Long suffix        42&, &HFF&             Force Long type
  Floating-point     3.14, 1.5E10, 2.5D3    Any number containing a decimal point or exponent is Double by default
  Single suffix      3.14!                  Force Single type
  Double suffix      3.14#                  Force Double type
.endtable

.note info
Both E and D can introduce an exponent (e.g. 1.5E10 and 2.5D3 are equivalent forms of a scientific-notation double).
.endnote

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

.h2 Boolean Values

Boolean values use -1 for True and 0 for False. Any non-zero numeric value is treated as True in a conditional context. The keywords True and False are reserved and may be used anywhere a Boolean value is expected.

.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). Parentheses override precedence and may be nested freely.

.table
  Precedence     Operator                  Description
  ----------     --------                  -----------
  1 (highest)    ^                         Exponentiation
  2              - (unary), + (unary)      Negation (unary plus is a no-op)
  3              *  /  \  MOD              Multiply, float divide, integer divide, modulus
  4              +  -                      Addition, subtraction (+ also concatenates strings)
  5              &                         String concatenation
  6              =  <>  <  >  <=  >=       Comparison (returns Boolean)
  7              NOT                       Logical/bitwise NOT
  8              AND                       Logical/bitwise AND
  9              XOR                       Logical/bitwise exclusive-or
  10             OR                        Logical/bitwise OR
  11             EQV                       Logical/bitwise equivalence
  12 (lowest)    IMP                       Logical/bitwise implication
.endtable

.h2 Arithmetic Operators

.table
  Operator   Description
  --------   -----------
  +          Addition (or string concatenation when both operands are strings)
  -          Subtraction (or negation when used as a unary prefix)
  *          Multiplication
  /          Floating-point division (result is always Single or Double)
  \          Integer division (result is Long, fractional part discarded)
  MOD        Integer modulus (remainder)
  ^          Exponentiation (result is Double)
.endtable

.h2 Comparison Operators

Comparison operators return True (-1) or False (0).

.table
  Operator   Description
  --------   -----------
  =          Equal to
  <>         Not equal to
  <          Less than
  >          Greater than
  <=         Less than or equal to
  >=         Greater than or equal to
.endtable

String comparisons are controlled by OPTION COMPARE. With OPTION COMPARE BINARY (the default) strings are compared by byte value. With OPTION COMPARE TEXT comparisons are case-insensitive.

.h2 Logical / Bitwise Operators

The logical operators work on Boolean values and also perform bitwise operations on integer values.

.table
  Operator   Description
  --------   -----------
  NOT        Logical/bitwise complement
  AND        Logical/bitwise AND
  OR         Logical/bitwise OR
  XOR        Logical/bitwise exclusive-or
  EQV        Logical/bitwise equivalence (same as NOT (a XOR b))
  IMP        Logical/bitwise implication (same as (NOT a) OR b)
.endtable

.h2 String Concatenation

Use & to concatenate strings. The + operator also concatenates when both operands are strings. Prefer & because it does not depend on operand types.

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

' + also concatenates when both operands are strings
greeting$ = "Hi " + name$
.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 : (colon). A line can be continued onto the next physical line by ending it with an underscore (_) preceded by whitespace. Comments start with ' (apostrophe) or the REM keyword and run to the end of the line. The character ? is a shorthand for PRINT.

.code
a = 10 : b = 20 : c = a + b        ' three statements on one line

total = price * quantity _
      + shipping + tax              ' one statement continued across lines

REM This is a comment
' So is this
? "Hello"                           ' same as PRINT "Hello"
.endcode

.link lang.declarations Declaration Statements (DIM, REDIM, CONST, TYPE, DECLARE)
.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 (ON ERROR, SHELL, SLEEP, END)

.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. If no type is given, the type defaults to whatever DEFtype (if any) is in effect for the variable's first letter; without a DEFtype statement the default is Single.

.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

Multiple variables can be declared at module level so their values persist between procedure calls. Arrays can have up to 8 dimensions. A variable declared with type suffix does not need the AS clause:

.code
Dim name$, count%, total&       ' suffixes infer the types
.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 at module level makes a variable accessible from every procedure without passing it as a parameter. Inside a SUB or FUNCTION, DIM declares a local variable that is recreated on each call (use STATIC to retain its value between calls).
.endnote

Fixed-length strings (STRING * n) are padded with spaces and truncated when assigned so their length is always exactly n.

.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, long, float, string, or boolean). Constants are not variables -- you cannot assign a new value to them or pass them by reference.

.code
CONST name = value
CONST name AS type = value
.endcode

.code
Const MAX_SIZE = 100
Const PI = 3.14159265
Const APP_NAME = "DVX App"
Const DEBUG_MODE = True
Const HEADER As String = "=== Report ==="
.endcode

Constants are scoped to the file or procedure in which they are declared. Constants declared at module level are visible to all procedures in the same module.

.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. This is rarely required because the compiler supports forward references within a module, but it is still accepted for compatibility:

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

.h2 DECLARE LIBRARY

Declares external functions from a native library bundled with DVX. This is how BASIC programs reach operating-system services, serial ports, databases, and other native facilities. Rather than writing DECLARE LIBRARY blocks yourself, add one of the shipped include files (such as commdlg.bas or sql.bas) to your project; the include file contains the proper declarations.

.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 "basrt"
    Declare Function SQLOpen(ByVal path As String) As Integer
    Declare Sub SQLClose(ByVal db As Integer)
End Declare
.endcode

.link lang.runtime See also: BASIC Runtime Libraries

.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. The variables must be the same type.

.code
SWAP variable1, variable2
.endcode

.code
Swap a, b
.endcode

.h2 SET

Assigns an object reference (form or control) to a variable. Required when creating a form or control with CreateForm / CreateControl so that the returned reference is stored in the variable:

.code
SET variable = objectExpression
.endcode

.code
Dim frm As Long
Set frm = CreateForm("MyForm", 320, 240)
frm.Caption = "Built in code"
.endcode

For ordinary numeric or string assignment, SET is not used.

.h2 ERASE

Frees the memory of a dynamic array and resets it to undimensioned state. Fixed-size arrays (declared with constant bounds) reset their elements but keep their shape.

.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 EXIT SUB
.index EXIT FUNCTION

.h1 Procedures

.h2 SUB...END SUB

Defines a subroutine (no return value).

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

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

Parameters are passed by reference by default. Use ByVal for value semantics; there is no separate ByRef keyword (omitting ByVal is the by-reference form). Use EXIT SUB to return early. A SUB is called either with or without parentheses; when used as a statement, parentheses are optional:

.code
Greet "World"
Greet("World")
Call Greet("World")
.endcode

.h3 Optional Parameters

Mark a parameter OPTIONAL to allow callers to omit it. An optional parameter must be positioned after all required parameters and receives an empty/zero default when not supplied.

.code
Sub Announce(ByVal msg As String, Optional ByVal loud As Integer)
    If loud Then
        Print UCase$(msg)
    Else
        Print msg
    End If
End Sub

Announce "hello"            ' loud defaults to 0
Announce "hello", True      ' loud is -1
.endcode

.h2 FUNCTION...END FUNCTION

Defines a function with a return value.

.code
FUNCTION name ([BYVAL] [OPTIONAL] 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. The function name begins with FN and is invoked just like a normal function. DEF FN functions cannot span multiple statements.

.code
DEF FNname(params) = expression
.endcode

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

Def FnCelsius(f As Double) = (f - 32) * 5 / 9
Print FnCelsius(212)  ' prints 100
.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

Writes expressions to the output window (or to a file channel).

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

.list
.item ; between items -- no separator (items appear next to each other, or separated by a space for numbers)
.item , between items -- advance to the next 14-column tab zone
.item A trailing ; or , suppresses the newline normally written at the end of the statement
.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 (first column is 1)
.endlist

.code
Print "Name:"; Tab(20); name$
Print "X="; x, "Y="; y        ' comma = next 14-column zone
Print #1, "Written to file"
.endcode

.h3 PRINT USING

PRINT USING formats each following expression according to a format string and prints the result. If more expressions are supplied than the format string consumes, the format string is reused from the start for each.

.table
  Format character   Meaning
  ----------------   -------
  #                  Digit (replaced with a digit or space to pad on the left)
  .                  Decimal-point position
  ,                  Insert thousands separator
  +                  At start or end: always show a sign character
  -                  At end: show a trailing minus sign only when negative
  **                 At start: fill leading spaces with asterisks
  $$                 At start: floating dollar sign
  ^^^^               Anywhere: format the value in scientific notation
  !                  First character of a string only
  &                  Entire string (variable length)
  \ ... \            Fixed-length string field (width = 2 + number of spaces between backslashes)
.endtable

.code
Print Using "###.##"; 3.14159             ' "  3.14"
Print Using "$$#,##0.00"; 1234567.89      ' "$1,234,567.89"
Print Using "**#,##0.00"; 42.5            ' "*****42.50"
Print Using "####.####^^^^"; 0.000123     ' scientific notation
Print Using "\  \"; "Hello"               ' fixed-width 4-char: "Hell"
Print Using "& likes &"; name$; food$
.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 (it is 0 when no error is active).

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

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

.h3 Common Error Numbers

.table
  Number   Meaning
  ------   -------
  1        FOR loop error (NEXT without FOR, NEXT variable mismatch, FOR stack underflow)
  4        Out of DATA
  7        Out of memory
  9        Subscript out of range / invalid variable or field index
  11       Division by zero
  13       Type mismatch / not an array / not a TYPE instance
  26       FOR loop nesting too deep
  51       Internal error (bad opcode)
  52       Bad file number or file not open
  53       File not found
  54       Bad file mode
  58       File already exists or rename failed
  67       Too many files open
  75       Path/file access error
  76       Path not found
.endtable

.h2 SHELL

Executes an operating-system command.

.code
SHELL "command"
.endcode

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

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

.h2 SLEEP

Pauses execution for the given number of seconds. With no argument, sleeps for 1 second.

.code
SLEEP [seconds]
.endcode

.h2 RANDOMIZE

Seeds the random number generator. Without an argument (not shown here) and without a prior RANDOMIZE, the sequence is the same on every run. Use RANDOMIZE TIMER to get a different sequence each run.

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

.h2 END

Terminates program execution immediately. Any form that is loaded is unloaded before the program exits.

.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.filesystem
.title File System Statements
.toc 1 File System Statements
.index KILL
.index NAME
.index FILECOPY
.index MKDIR
.index RMDIR
.index CHDIR
.index CHDRIVE
.index GETATTR
.index SETATTR
.index File Attributes

.h1 File System Statements

DVX BASIC provides statements for working with the file system -- creating, deleting, renaming, and copying files and directories, and reading or setting file attributes.

.h2 KILL

Deletes a file.

.code
KILL filename$
.endcode

.code
Kill "temp.bak"
.endcode

.h2 NAME ... AS

Renames (or moves) a file.

.code
NAME oldName$ AS newName$
.endcode

.code
Name "draft.txt" As "final.txt"
.endcode

.h2 FILECOPY

Copies a file. If the destination already exists it is overwritten.

.code
FILECOPY source$, destination$
.endcode

.code
FileCopy "data.db", "data.bak"
.endcode

.h2 MKDIR / RMDIR

Creates or removes a directory.

.code
MKDIR path$
RMDIR path$
.endcode

.code
MkDir App.Data & "\backups"
RmDir "C:\OLD"
.endcode

.h2 CHDIR / CHDRIVE

Changes the current working directory or drive.

.code
CHDIR path$
CHDRIVE drive$
.endcode

.code
ChDir "C:\DVX\PROJECTS"
ChDrive "D"
.endcode

.h2 GETATTR / SETATTR

GETATTR returns the attributes of a file (as a function). SETATTR sets them (as a statement). Attributes are a bitmask of the vb file-attribute constants.

.code
attrs = GETATTR(filename$)
SETATTR filename$, attrs
.endcode

.table
  Constant       Value    Attribute
  --------       -----    ---------
  vbNormal       0        Normal file (no attributes set)
  vbReadOnly     1        Read-only
  vbHidden       2        Hidden
  vbSystem       4        System file
  vbDirectory    16       Entry is a directory
  vbArchive      32       File has been modified since last backup
.endtable

.code
If (GetAttr("readme.txt") And vbReadOnly) <> 0 Then
    Print "File is read-only."
End If

SetAttr "secret.dat", vbHidden + vbReadOnly
.endcode

.h2 CURDIR$ / DIR$

CURDIR$ returns the current directory. DIR$ returns the first file matching a pattern; subsequent calls with no arguments return additional matches (or "" when done).

.code
cwd$ = CURDIR$
first$ = DIR$("*.txt")
WHILE first$ <> ""
    Print first$
    first$ = DIR$        ' next match, no argument
WEND
.endcode

.h2 FILELEN

Returns the length of a file in bytes.

.code
bytes = FILELEN(filename$)
.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 the first character of s$
  CHR$(n)                           String    Character with ASCII code n
  FORMAT$(value, fmt$)              String    Formats a numeric value using a format string
  HEX$(n)                           String    Hexadecimal representation of n (uppercase, no leading &H)
  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 (1-based)
  LCASE$(s$)                        String    Converts s$ to lowercase
  LEFT$(s$, n)                      String    Leftmost n characters of s$
  LEN(s$)                           Integer   Length of s$ in characters
  LTRIM$(s$)                        String    Removes leading spaces from s$
  MID$(s$, start)                   String    Substring from start (1-based) to end of string
  MID$(s$, start, length)           String    Substring of length characters starting at start
  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 (leading space for non-negative)
  STRING$(n, char)                  String    String of n copies of char (char can be an ASCII code or single-character string)
  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; stops at first non-numeric character
.endtable

.h2 FORMAT$

FORMAT$ formats a numeric value using a BASIC-style format string. The format characters are the same as the ones used by PRINT USING.

.code
s$ = FORMAT$(value, fmt$)
.endcode

.code
Print Format$(3.14159, "###.##")      ' "  3.14"
Print Format$(42, "00000")            ' "00042"
Print Format$(1234.5, "#,##0.00")     ' "1,234.50"
Print Format$(0.5, "PERCENT")         ' "50%"
.endcode

The accepted format characters are # (digit or pad space), 0 (digit or pad zero), . (decimal point), , (thousands separator), + and - (sign placement), $$ (floating dollar sign), ** (asterisk fill), and the literal word PERCENT (multiplies by 100 and appends %). See PRINT USING for details on each.

.h2 MID$ Assignment

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

.code
Mid$(s$, start [, length]) = replacement$
.endcode

.code
Dim s$
s$ = "Hello, World!"
Mid$(s$, 8, 5) = "DVX--"
Print s$                   ' Hello, DVX--!
.endcode

If length is omitted, MID$ replaces up to LEN(replacement$) characters. The target string's total length never changes -- extra characters in replacement$ are truncated and shorter replacements leave trailing characters in place.

.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 (result in radians)
  COS(n)     Double    Cosine of n (n in radians)
  EXP(n)     Double    e raised to the power n
  FIX(n)     Integer   Truncates n toward zero (drops the 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 in the range 0 <= RND < 1
  SGN(n)     Integer   Sign of n: -1 if negative, 0 if zero, 1 if positive
  SIN(n)     Double    Sine of n (n in radians)
  SQR(n)     Double    Square root of n
  TAN(n)     Double    Tangent of n (n in radians)
  TIMER      Double    Seconds since midnight
.endtable

.note info
RND with no argument returns the next number in the sequence. Use RANDOMIZE or RANDOMIZE TIMER to seed the generator so you don't get the same sequence each run.
.endnote

.h2 Color Functions

The color functions work with 24-bit RGB colors packed into a Long.

.table
  Function           Returns   Description
  --------           -------   -----------
  RGB(r, g, b)       Long      Combine red, green, and blue components (0-255) into a 24-bit color
  GETRED(color)      Integer   Red component (0-255) of a color built with RGB
  GETGREEN(color)    Integer   Green component (0-255) of a color built with RGB
  GETBLUE(color)     Integer   Blue component (0-255) of a color built with RGB
.endtable

.code
Dim c As Long
c = RGB(255, 128, 0)           ' bright orange
Print GetRed(c); GetGreen(c); GetBlue(c)    ' 255 128 0
Me.BackColor = RGB(0, 0, 128)  ' dark blue background
.endcode

.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 (rounds half away from zero)
  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 the file pointer is at end of file
  FREEFILE                    Integer   Next available file channel number (1..16)
  INPUT$(n, #channel)         String    Reads exactly 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)
  FILELEN(path$)              Long      Length of the named file in bytes (no OPEN needed)
  GETATTR(path$)              Integer   File attribute bits (see vbReadOnly, vbHidden, etc.)
  CURDIR$                     String    Current working directory
  DIR$(pattern$)              String    First filename matching pattern, or ""
  DIR$                        String    Next match from the last DIR$(pattern$), or "" when done
  LBOUND(array [, dim])       Integer   Lower bound of an array dimension (default dim = 1)
  UBOUND(array [, dim])       Integer   Upper bound of an array dimension (default dim = 1)
.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" (24-hour)
  TIMER             Double    Seconds since midnight
  ENVIRON$(name$)   String    Value of the environment variable; empty string if not set
  ERR               Integer   Current runtime error number (0 if no error)
  SHELL(cmd$)       Integer   Exit code of the command (also usable as a statement, discarding the code)
.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 Nothing
.index DoEvents
.index DOEVENTS
.index MsgBox
.index MSGBOX
.index InputBox$
.index INPUTBOX$
.index CreateForm
.index CreateControl
.index SetEvent
.index RemoveControl
.index With
.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. A form is normally designed visually in the IDE and saved as a .frm file, but forms and their controls can also be built entirely in code.

.h2 Loading and Unloading Forms

.code
LOAD FormName
UNLOAD FormName
.endcode

LOAD creates the form and its controls in memory. It fires Form_Load when the form is first loaded. UNLOAD destroys the form, firing Form_QueryUnload (which can cancel the close) and then Form_Unload. The form name here is the literal name of the form as it appears in its .frm file.

.h2 Showing and Hiding Forms

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

Pass vbModal (1) to Show for a modal dialog that blocks until the user closes it. Omit the mode for a modeless (non-blocking) window.

.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 -- that is, the form whose event handler is running. Use it to access the form's own properties, controls, and methods from within event handlers, especially when the form's name may change or when the same code runs from multiple forms.

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

.h2 Nothing

Nothing is a null object reference. Assign it to an object-typed variable to indicate "no object".

.code
Set myCtrl = Nothing
.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 WITH

The WITH block provides a shorthand for setting several properties on the same control or for making several method calls. Inside the block, begin each property or method with a dot and omit the control name.

.code
WITH ControlName
    .Property1 = value1
    .Property2 = value2
    .Method arg1, arg2
END WITH
.endcode

.code
With Label1
    .Caption = "Status: Ready"
    .ForeColor = RGB(0, 128, 0)
    .Visible   = True
End With
.endcode

.h2 Building Forms in Code

In addition to loading forms from .frm files, you can build a form entirely from code with CreateForm, CreateControl, SetEvent, and RemoveControl. The returned reference should be stored with SET.

.h3 CreateForm

.code
SET formVar = CreateForm(name$, width%, height%)
.endcode

Creates a new form with the given name and initial size. Returns a form reference.

.h3 CreateControl

.code
SET ctrlVar = CreateControl(formRef, typeName$, ctrlName$ [, parentCtrlRef])
.endcode

Creates a control on the given form. typeName$ is the control type (e.g. "CommandButton", "Label", "TextBox"). ctrlName$ is the unique name for the new control. If a parentCtrlRef is supplied, the new control is nested inside it (useful for placing controls inside containers like HBox or Frame).

.h3 SetEvent

.code
SETEVENT ctrlRef, eventName$, handlerName$
.endcode

Wires an arbitrary SUB as the handler for a control's event. The default event-handler convention (ControlName_EventName) is used automatically for controls defined in a .frm file; SetEvent is for controls you create dynamically or for reusing a single handler across multiple controls.

.h3 RemoveControl

.code
REMOVECONTROL formRef, ctrlName$
.endcode

Removes a control from a form.

.code
Dim frm As Long
Dim lbl As Long

Set frm = CreateForm("MyDlg", 300, 200)
frm.Caption = "Built in code"

Set lbl = CreateControl(frm, "Label", "StatusLabel")
StatusLabel.Caption = "Hello, world!"

Dim btn As Long
Set btn = CreateControl(frm, "CommandButton", "BtnClose")
BtnClose.Caption = "Close"
SetEvent btn, "Click", "OnCloseClick"

frm.Show

Sub OnCloseClick
    Unload Me
End Sub
.endcode

.h2 DoEvents

Yields control to DVX so the GUI can process pending events. Call this in long-running loops to keep the UI responsive (otherwise the window will appear frozen).

.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 the result) or as a function (returns the button clicked).

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

flags is the sum of a button-style constant and an icon constant. See Predefined Constants for the complete list.

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

.h2 InputBox$

Displays an input dialog and returns the user's text entry. Returns an empty string if the user cancels.

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

.code
name$ = InputBox$("Enter your name:", "Name Entry", "")
If name$ <> "" Then
    Print "Hello, "; name$
End If
.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 or text changed
  KeyPress             Printable key was pressed (receives ASCII code)
  KeyDown              Any key was pressed (receives key code and shift state)
  KeyUp                Key was released
  MouseDown            Mouse button pressed (receives button, X, Y)
  MouseUp              Mouse button released
  MouseMove            Mouse moved over the control
  Scroll               Control was scrolled (mouse wheel or scrollbar)
  GotFocus             Control received input focus
  LostFocus            Control lost input focus
  Form_Load            Form is being loaded (fires once, after controls are created)
  Form_QueryUnload     Form is about to close; set Cancel = 1 to abort
  Form_Unload          Form is being unloaded
  Form_Resize          Form was resized
  Form_Activate        Form gained focus
  Form_Deactivate      Form lost focus
  Timer1_Timer         Timer control interval elapsed (Timer control's default event)
.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 SQLite database support through the sql.bas include library. Add sql.bas to your project to gain access to these 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 (> 0) or 0 on failure. The file is created if it does not exist.

.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.). Returns True on success.

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

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

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

.h3 SQLNext

Advances the cursor to the next row. Returns True if a row is available, False when there are no more rows.

.code
hasRow = SQLNext(rs)
.endcode

.h3 SQLEof

Returns True if the cursor is past the last row.

.code
done = SQLEof(rs)
.endcode

.h2 Reading Fields

.h3 SQLField$ / SQLFieldText$

Returns a field value as a string. Use SQLField$ to look up by column name; use SQLFieldText$ to look up by 0-based column index.

.code
value$ = SQLField$(rs, columnName$)
value$ = SQLFieldText$(rs, columnIndex)
.endcode

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

.h3 SQLFieldName$

Returns the column name for a given 0-based column index.

.code
colName$ = SQLFieldName$(rs, columnIndex)
.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 cursor. Always call this when finished 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 Integer
Dim rs As Integer

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 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 (the same text format used by DVX system configuration).

.h2 IniRead

Reads a value from an INI file. Returns the default value if the file, section, or key is not found. All four arguments are required.

.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 vbNormal
.index vbReadOnly
.index vbHidden
.index vbSystem
.index vbDirectory
.index vbArchive
.index True
.index False
.index Predefined Constants

.h1 Predefined Constants

The following constants are predefined by the compiler and available in all programs. No DIM or CONST declaration is required to use them.

.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 (with + or OR) to display an icon in the message box.

.table
  Constant        Value   Description
  --------        -----   -----------
  vbInformation   &H10    Information icon (i)
  vbExclamation   &H20    Warning icon (!)
  vbCritical      &H30    Error/critical icon (X)
  vbQuestion      &H40    Question 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 File Attribute Flags

Bit values used with GETATTR and SETATTR.

.table
  Constant      Value   Description
  --------      -----   -----------
  vbNormal      0       Normal file (no attributes)
  vbReadOnly    1       Read-only
  vbHidden      2       Hidden
  vbSystem      4       System file
  vbDirectory   16      Entry is a directory
  vbArchive     32      File has been modified since last backup
.endtable

.h2 Boolean Constants

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

.topic lang.runtime
.title Include Libraries
.toc 1 Include Libraries
.index Include Libraries
.index commdlg.bas
.index sql.bas
.index comm.bas
.index resource.bas
.index help.bas
.index DECLARE LIBRARY

.h1 Include Libraries

DVX ships a set of BASIC include files (.bas) in the sdk/include/basic directory. Each file is a small library of DECLARE LIBRARY wrappers around native DVX runtime functions. Add an include file to your project (the IDE's Add File command, or editing the .dbp with another tool) and the declared functions become available to your code.

.table
  File           Provides
  ----           --------
  commdlg.bas    File Open/Save dialogs, input dialogs, choice dialogs, save-prompt dialogs
  sql.bas        SQLite database access (SQLOpen, SQLQuery, SQLNext, SQLField$, etc.)
  comm.bas       Serial-port I/O (raw and packet) and optional encrypted links
  resource.bas   Read and write DVX resource blocks (icons, text, binary data) in bundled files
  help.bas       Compile help source files and open the DVX help viewer
.endtable

.h2 Using an Include Library

.code
' With commdlg.bas added to the project
Dim path As String
path = basFileOpen("Open a file", "Text Files (*.txt)|All Files (*.*)")

If path <> "" Then
    Print "Selected: " & path
End If
.endcode

.note info
DVX BASIC does not have an $INCLUDE directive. Libraries are added to the project so that the compiler sees their DECLARE LIBRARY blocks.
.endnote

.link lib.basrt See also: BASIC Runtime Library
