xonoBASIC Language Reference
xonoBASIC is based on the classic BASIC language, designed for a new purpose: Web programming.
It is a subset of QBasic and QuickBasic without the keyboard commands. xonoBASIC is predestinated for CGI work and dynamic generation of HTML. And best of all it's easy to learn and understand.
Initialization File
Variables and Constants
Expressions
HTML Basic
Output Commands
Conditional, Looping and Branching Commands
File and Directory Commands
Database Commands- SQL and ODBC
String Commands and Functions
Number Commands and Functions
Date and Time Commands and Functions
Graphics Commands
Internet and CGI Commands and Functions
Miscellaneous Commands and Functions
Index
© 2016 xonoCODE.com All Rights Reserved
This product uses parts of the iMatix SFL, Copyright © 1991-2000 iMatix Corporation http://www.iMatix.com
Programmer's Notepad 2 Copyright (c) 2002-2014 Simon Steele Mongoose Copyright (c) 2004-2010 Sergey Lyubka
Special thanks to Daniel Bailey for providing the base code and support.
Initialization File
xonoBASIC Interpreter reads a file on startup that allows certain parameters to be set. The filename is xonoBASIC.ini. The file is first checked in the Windows directory (as identified by the WINDIR environment variable), and then if not found, the current directory (usually the same where the server executable resides) or the webroot (make sure to disallow access to ini files in that case).
The format of the file is as follows:
[MISC]
scriptdir=c:\webroot\ startdir=c:\webroot\ uploaddir=c:\webroot\uploads\ uploadallowed=Y uploaddiroverrideallowed=Y emailvia=283.43.95.19 emailfrom=myname@mydomain.com emailallowed=Y
shellallowed=Y looplimit=50000
All entries are optional and do not have to exist. The keywords have the following meanings:
scriptdir The directory where your scripts are located.
startdir The directory to start in, the program changes directory to here before starting execution of your program.
uploaddir The directory to upload files to. Non existing folders will be automatically created.
uploadallowed HTTP file uploads allowed(Y default), or not allowed(N). If not allowed, the file is still sent, but not written to disk.
uploaddiroverrideallowed Allows to override the uploaddir settings from within a script via the uploaddiroverride("") directive. (Y default)
emailvia The computer name or IP address of the SMTP server to send email to.
emailfrom All email will be from this address, unless specified in the EMAIL command.
emailallowed Y or N, default Y. If N, the EMAIL command is disabled.
shellallowed Y or N, default Y. If N, the SHELL command is disabled.
looplimit Maximum number of loop iterations, -1 (infinite), 99999 (default). Useful for preventing infinite loops.
Variables and Constants
There are three kinds of variables in xonoBASIC, numeric, string, and date/time. Variable names may be up to 30 characters long. String variables end with the $ character, numeric and date variables do not. Date variables and actually numbers, one uses date functions to display dates.
Because date variables are numeric, date arithmetic is supported. One dimensional arrays are supported, and the DIM command also. Here are some example variable names:
name$ - String variable that holds up to 1000 characters.
total - Numeric variable that holds integer and floating point numbers.
address$(2) - Array String variable, 2 is the subscript
tot(1) - Array Numeric variable, 1 is the subscript
DIM tot(100) - Array Numeric variable, 0..100 is the subscript
REDIM tot(200) - Redimension an existing array
In xonoBASIC, total and total$ is one variable expressed as a number and a string. There are only global variables, and variables do not need to be declared before use. The first occurrence of a variable (including array variables) creates it with a string value of "" and a numeric value of 0. xonoBASIC does not use specific data type settings like single/double/long/integer/string.
Numerical variables can have a length of 17 digits. If a number is larger, the 17th digit is rounded and anything behind gets truncated to zeros.
Example: 2342534545343445345 becomes 2342534545343445500
Floating point variables can have a length of 13 digits. If a number is larger, the 17th digit is rounded and anything behind gets truncated
Example: 234.123456789876 becomes 234.1234567899
String variables can be up to 8000 characters long.
Constants are created with the CONST keyword in front of an assignment commands, ex. CONST MAX_SIZE=10
There are also predefined variables for the CGI environment.
CGI Environment Variables
CGI Name Variable Name
AUTH_TYPE AUTH_TYPE$
CONTENT_LENGTH CONTENT_LENGTH
CONTENT_TYPE CONTENT_TYPE$
DOCUMENT_ROOT DOCUMENT_ROOT$
GATEWAY_INTERFACE GATEWAY_INTERFACE$
HTTP_ACCEPT HTTP_ACCEPT$
HTTP_COOKIE HTTP_COOKIE$
HTTP_FROM HTTP_FROM$
HTTP_REFERER HTTP_REFERER$
HTTP_USER_AGENT HTTP_USER_AGENT$
PATH_INFO PATH_INFO$ (Each part of the path may also be accessed using PATH_INFO$(1), PATH_INFO$(2), ...)
PATH_TRANSLATED PATH_TRANSLATED$
QUERY_STRING QUERY_STRING$
REMOTE_ADDR REMOTE_ADDR$
REMOTE_HOST REMOTE_HOST$
REMOTE_IDENT REMOTE_IDENT$
REMOTE_USER REMOTE_USER$
REQUEST_METHOD REQUEST_METHOD$
SCRIPT_NAME SCRIPT_NAME$
SERVER_NAME SERVER_NAME$
SERVER_PROTOCOL SERVER_PROTOCOL$
SERVER_SOFTWARE SERVER_SOFTWARE$
REDIRECT_STATUS REDIRECT_STATUS$
PROGRAMS_ROOT PROGRAMS_ROOT$
SERVER_ROOT SERVER_ROOT$
SERVER_PORT SERVER_PORT$
SCRIPT_FILENAME SCRIPT_FILENAME$
HTTPS HTTPS$
Other predefined variables and constants:
Other Variables and Constants
Variable Name Description
ERR Numeric variable set on file operations, 0 is success.
OSTYPE$ Type of operating system, "WIN" if Windows, or "UNIX" for Unix or Linux.
PI Mathematical constant of PI
UPLOAD_COUNT Number of files uploaded via browser file upload
UPLOAD_FILE$ Filename of uploaded file. If multiple files are uploaded, UPLOAD_FILE$(0) contains filename of first file, UPLOAD_FILE$(1) the 2nd file, etc.
UPLOAD_TYPE$ The content type of the uploaded file. If multiple files, UPLOAD_TYPE$(0) for the first file, UPLOAD_TYPE$(1) the 2nd, etc.
UPLOAD_CLIENT_FILE$ Filename of client(browser) side file, if multiple files uploaded, UPLOAD_CLIENT_FILE$(0) contains filename of first file, UPLOAD_CLIENT_FILE$(1) the 2nd file, etc.
UPLOAD_FILESIZE The file size of the uploaded file. If multiple files, UPLOAD_FILESIZE(0) for the first file, UPLOAD_FILESIZE(1) the 2nd, etc.
QUERYFIELD_NAME$ This array variable holds the name of the query fields in the URL. It gives a simple method of looking at QUERY_STRING$. Most query string values are passed as name=value pairs. Note that name=value query fields are automatically defined as a xonoBASIC variable, and that this variable is an alternative. For instance, if the query string is ?a=1&b=dbname, then a variable named "a$" and "b$" are automatically created with the values of "1" and "dbname".
QUERYFIELD_NAME$(1) for the first file, QUERYFIELD_NAME(2)
QUERYFIELD_VALUE$ This array variable holds the value of the value part of a name=value QUERY_STRING. QUERYFIELD_VALUE$(1) for the first value, QUERYFIELD_VALUE(2) the 2nd, etc.
This array variable holds the names of form fields.
FORMFIELD_NAME$ FORMFIELD_NAME$(1) the first field, FORMFIELD_NAME$(2) the 2nd, etc. Note that form fields are automatically defined as a xonoBASIC variable, and that this variable is an alternative way of looking at the form data.
FORMFIELD_VALUE$ This array variable holds the value of form fields. FORMFIELD_VALUE$(1) the first field, FORMFIELD_VALUE$(2) the 2nd, etc.
QUOTE$ The " character, same as chr$(34)
XNBVERSION$ The xonoBASIC version number.
Expressions and Operators
xonoBASIC supports the basic mathematically expressions, string expressions and standard operators.
To concatenate two strings, use the + operator: name$ + " was here".
Mathematically expressions consist of operators ( + - * / ^ % ) and numeric constants and variables.
Example: a = a + (5+c) / 2.
There are both Commands and Functions in xonoBASIC. A functions always encloses its arguments within parenthesis, ex. sin(30), and Commands do not use parenthesis around its argument, ex. PRINT "Hello".
A TRUE condition will return -1 A FALSE condition will return 0
Arithmetic operators Relational/logical operators
- Negation (unary op.) = Equal To
+ Addition <> Not Equal To
- Subtraction (binary op.) < Less Than
* Multiplication <= Less Than or Equal To
/ Division > Greater Than
^ Exponentiation => Greater Than or Equal To
% Modulus IN Element of (sample below)
AND Bit wise AND
OR Bit wise OR
NOT Bit wise NOT
XOR Bit wise XOR
Grouping operator
( ) Grouping
IN / NOT IN example:
s$ = "e"
if (s$ in ("a","e","i","o","i")) then ? "A vowel" : else print "Consonant" b=10
if (b not in (10,20,30,40,50)) then print "bad" else print "good"
HTML Basic
xonoHTMLBasic is an extra feature of the xonoBASIC language and is similar to Microsoft's ASP or PHP.
xonoHTMLBasic allows you to add BASIC language programming to HTML. Consider this example:
<% for j = 1 to 5 %>
I Love Number: <%=j%>
<% next %>
The BASIC code starts with <% and ends with %>. Everything else is treated as HTML. If an = follows <% then the value of the variable or expression that follows is printed at that position. of course, you can also use the standard print statement though, like <% print j %>.
xonoBASIC automatically supports xonoHTMLBasic. Simply name your file with an extension of htxnb (ex. myfile.htxnb) and reference the file the same way xonoBASIC files are referenced.
Visit xonoCODE.com for more informations.
Anyway, this style of programming is depreciated. Try to keep dynamic code seperated from HTML.
Mixed code is just to hard to maintain or debug.
The $INCLUDE function is not available in xonoHTMLBasic.
Script Encoding
With xonoBASIC you can encode your scripts to protect them from being viewed or altered.
Encoded scripts can still be executed by others.
If you are using xonoEDIT, you can simply press F11 to generate an encoded version of the currently opened script.
Make sure to save the file first as this function needs the source script to be physically present on your disk to encode it and automatically prepend enc- to the filename of the newly generated file.
Syntax: xonoBASIC.exe -e sourcefile destinationfile
Example:
c:\xonoBASIC.exe -e c:\script.xnb c:\scriptencoded.xnb
INDEX
Initialization File
Expressions
Output Commands
File and Directory Commands
CGI Commands and Functions
Conditional and Branching Commands
Database Commands- SQL and ODBC
Date and Time Commands and Functions
Graphics Commands
Internet Commands and Functions
Miscellaneous Commands and Functions
Number Commands and Functions
String Commands and Functions
ABS
APPEND
ASC
ATN
CASE / SELECT
CALL / SUB
CENTER$
CHDIR
CHR$
CIRCLE
CLOSE
COLON :
COLOR TABLE
COMMAND$
CONTENTTYPEHTML
CONTENTTYPEIMAGE
CONTENTTYPEPLAIN
COPY
COS
CRUNCH$
CSV$
CTIME
CURDIR$
DATA
DATE$
DECTODEGMINSEC
DEGMINSECTODEC
DIM / REDIM
DSTANCE
DO ... LOOP
DOCTYPEHTML
DOLLAR$
DOUBLEQUOTE$
DRAW
EMAIL
ENCODE / DECODE
END
ENVIRON$
EOF
ERASE
EXIT DO
EXIT FOR
EXIT WHILE
EXP
EXTRACT$
FILEEXISTS
FILEISEXECUTABLE
FILEISFOLDER
FILEISLEGAL
FILEISPROGRAM
FILEISREADABLE
FILEISWRITEABLE
FILES
FILESIZE
FILETIMESTAMP
FIX
FOR / NEXT
FORMATDATE$
FORMATTIME$
FREEFILE
FUNCTION
GOSUB / RETURN
GOTO
HEX$
HTMLDECODE
HTMLENCODE
HTTPGET
HTTPPOST
IF / THEN / ELSE
IMAGE
INCLUDE
INITCAP$
INSTR
KILL
LBOUND / UBOUND
LCASE$
LEFT$
LEN
LINE
LINE INPUT
LOAD$
LOANAMT
LOANPCT
LOANPMT
LOANTERM
LOCK
LOCATE
LOF
LOG
LOG10
LOOP
LPAD$
LTRIM$
MATCH
MAX
MID$
MIN
MKDIR
MOD
MOVE
NOHEADER
NOW
OCT$
ODD
ORDINAL$
PAINT
PRINT USING
PRINT
PSET
RANDOMIZE
READ
REM
RENAME
REPLACE$
RESTORE
RETURN / GOSUB
REVERSE$
RGB
RIGHT$
RMDIR
RND
ROMAN$
RPAD$
RTRIM$
SAVE$
SCREEN
SELECT CASE
SGN
SHELL$
SHOWIMAGE
SIMILAR
SIN
SLEEP
SOUNDEX$
SPACE$
SPLIT
SQLCOLUMNS
SQLCONNECT
SQLDISCONNECT
SQLEXEC
SQLTABLES
SQR
STR$
STRING$
SUB / CALL
SWAP
TAG$
TAN
TIME$
TIMER
TRIM$
UCASE$
UNLOCK
URLDECODE
URLENCODE
VAL
VALUEOF$
WEEKDAY
WHILE / WEND
WRITE
© 2016 xonoCODE.com All Rights Reserved
Output Commands
There are three commands used by xonoBASIC to output data :
ECHO
PRINT / WRITE
ECHO
Syntax: ECHO characters to output
or
!characters to output
The ECHO command outputs whatever follows the word ECHO or ! until the end of line. Variables or functions are not evaluated as part of this command, it simply provides an easy way to output characters. Example:
ECHO Welcome To My Home Page for j = 1 to 10
!Hello World 10 Times next
PRINT and WRITE
Syntax:
PRINT [#filenumber,] [USING picture;][expressionlist] [{; | ,}] WRITE [#filenumber,] [expressionlist]
Usually you will use the PRINT or ECHO command to output HTML. You may also use ? (ex. ? "Hello") instead of the word PRINT. If an IMAGE command is active, then PRINT and WRITE write to the open image file. Example:
PRINT "Hello ", name$
PRINT USING "Amount is: $$###,###,###.##"; amt PRINT USING "& $$###,###.##"; "Tax is "; amt * .06
WRITE #1,date$,a,b,c
The USING clause is optional, and picture may be the following:
Characters Used to Format a Numeric Expression
# Digit position - Placed after digits, print tailing
. Decimal point - if negative
, Use the thousands separator $$ Print dollar sign
^^^^ Use exponential format ** Asterick fill
Characters Used to Format a String
& Prints entire string \ \ Prints first n characters where n
! Prints first character is number of characters between the backslashes + 2.
Any other character in the picture is printed as is. To print a picture character, precede it with an _ (ex. _$).
Conditional, Looping and Branching Commands
IF / THEN / ELSE
SELECT CASE
FOR / NEXT
EXIT FOR
DO ... LOOP
EXIT DO
WHILE / WEND
EXIT WHILE
GOTO
GOSUB / RETURN
FUNCTION
SUB / CALL
IF / THEN / ELSE
Syntax: IF condition THEN action/condition
or:
IF condition THEN action/condition ELSE
action/condition END IF
There are two types of IF commands, single line and multiline. A single line IF command is written on one line, while multiline occurs on more than one line and end with a required END IF word. The IF command evaluates an expression and if true executes the code immediately following the required THEN keyword, if the expression evaluates to false, execution jumps to either the end of the if or the optional ELSE command. Embedded ifs (if within an if) are supported. Muliple conditions are supported. Use the AND and OR keywords to connect the conditions, use parenthesis around each condition to ensure proper evaluation. The NOT keyword is now supported also.
Example:
REM Single line if
If name$ = "Paul" Then Print "Greetings Paul" else Print "Do I know you?"
REM Multiline if
if name$ = "Paul" then print "Greeting Paul" else
print "Do I know you?" end if
REM Multiple conditions
IF (cnt>10) AND (name$ <> "") THEN print name$;" has ";cnt;" books."
SELECT CASE
Executes a statement block depending on an expression. The expression can be string or numeric. Example:
amt=200.50 SELECT CASE amt CASE 1,2,4,8,16
PRINT "Amount is a power of 2 less than 17" CASE 1 TO 100
PRINT "Amount is between 1 and 100" CASE 101 TO 200
PRINT "Amount is between 100 and 200" CASE IS > 200
PRINT "Amount is more than 200" CASE ELSE
PRINT "Amount should not be less than zero." END SELECT
FOR / NEXT
Syntax: for var = start to end [STEP n]
The FOR command is used to execute a block of code for a fixed number of times. It executes the block of code for each iteration from start to end. The block of code starts on the line after the for and until the required NEXT command. For blocks may be nested 10 levels.
Example:
For Counter = 1 To 5
Print "The value of Counter is ", Counter
REM Notice how Counter automatically has a string value also Print "The value of Counter is ", Counter$
Next
EXIT FOR
Syntax: EXIT FOR
The EXIT FOR command is used to immediately exit a FOR loop. Example:
amt=100
For Counter = 1 To 5 amt=amt+100
Print "The value of amt is ", amt if amt > 300 then exit for
Next
DO ... LOOP
Syntax:
DO [{WHILE | UNTIL} condition] [statementblock]
LOOP DO
[statementblock]
LOOP [{WHILE | UNTIL} condition]
The DO command repeats a block of statements while a condition is true (WHILE) or until a condition becomes true (UNTIL).
Example:
a=0
DO UNTIL a > 10
Print "The value of a is ", a a = a + 1
LOOP
EXIT DO
Syntax: EXIT DO
The EXIT DO command is used to immediately exit a DO loop. Example:
DO
if x < 0 then exit do x=x+1
LOOP UNTIL x>20
WHILE / WEND
Syntax:
WHILE cond command command WEND
The WHILE command is used to execute a block of code while a condition is true. Example:
WHILE a < 10
Print "The value of a is ", a a = a + 1
WEND
EXIT WHILE
Syntax: EXIT WHILE
The EXIT WHILE command is used to immediately exit a WHILE loop. Example:
WHILE a < 10
Print "The value of a is ", a if a = 4 then exit while
a = a + 1 WEND
GOTO
Syntax:
GOTO n ' a number GOTO label ' a label
GOTO branches execution to a label defined elsewhere in the program. Once a GOTO finds a matching label, execution continues on from the Label forward.
Example:
Goto 100
Print "You won't see this print!"
rem this goto will not execute either goto finish
100
Print "After 100 label" rem Here is another label finish:
print "Now we are finished"
GOSUB / RETURN
GOSUB is like Goto, except the RETURN statment will return to the command after GOSUB.
The code after the label until the RETURN is known as a subroutine. Normally, subroutines are defined at the end of the program.
Example:
Gosub 100
Print "The value of a is ",a Gosub mysub
Print "The value of a is ",a End
100
a = a + 10 return mysub:
a = a - 10 return
FUNCTION
Syntax: FUNCTION functionname$([par1] [, par2])
FUNCTION() defines a code block and returns the result to the function call. You can pass additional parameters along with your function call.
Example:
function myfunc$(a$) myfunc$ = "this is a " + a$ end function
print myfunc$("test")
SUB / CALL
Syntax:
CALL subname([par1] [, par2]) SUB subname([var1] [,var2]) command
END SUB
SUB() defines a subroutine that can be accessed with the CALL command. It's sort of a combination of GOSUB / RETURN and the FUNCTION command, as SUB / CALL also allows passing parameters to the subroutine.
Example:
call mysub("test") sub mysub(t$) print t$
end sub
File and Directory Commands
APPEND
CHDIR
CLOSE
CURDIR$
EOF
FILES
FREEFILE
FILEEXISTS
FILEISEXECUTABLE
FILEISFOLDER
FILEISLEGAL
FILEISPROGRAM
FILEISREADABLE
FILEISWRITEABLE
FILESIZE
FILETIMESTAMP
COPY
MOVE
KILL
LINE INPUT
LOCK
LOF
MKDIR
OPEN
PRINT
PRINT USING
WRITE
RENAME
RMDIRUNLOCK
OPEN
Syntax: Open filename$ FOR APPEND/INPUT/OUTPUT AS #filenum
Opens a text file for reading (INPUT) or writing (APPEND, OUTPUT). APPEND adds to the end of the file. Binary files are not currently supported.
Example:
Open "log.txt" for output as #1
print #1, "This will be written to file log.txt" close #1
CLOSE
Syntax: CLOSE [#filenum]
Closes a previously opened file. Example:
print "Content-type: text/plain"
print
REM ---- Show the file identified by fn$ where fn is passed as part of the REM query string or as an input field on a form.
REM Example URL: showfile.xnb?fn=myfile.txt open fn$ for input as #1
if err <> 0 then print "File "+fn$+" not found!" : end
100 line input #1, s$ print s$
if eof(1) = 0 then goto 100 close
CURDIR$
Syntax: $ = CURDIR$
Example:
print "The current directory is: ";curdir$ chdir ".."
print "The current directory is now: ";curdir$
LINE INPUT
Syntax: LINE INPUT #filevar, varname$
This command reads a line in a text file. To read standard delimited files, use LINE INPUT in conjunction with SPLIT and EXTRACT$.
Example:
Open "log.txt" for input as #1 REM Read 1 line and display it line input #1, s$
print s$ close #1
EOF
Syntax: # = EOF(filevar)
EOF is a function that returns a 0 if the file referred to by filevar is not at end of file or -1 otherwise. End of file is reached when the last line of a file is read via LINE INPUT. Example:
Open "log.txt" for input as #1
REM Read all lines and display it in upper case.
100 line input #1, s$ print ucase$(s$)
if eof(1) = 0 then goto 100 close #1
APPEND
Syntax: APPEND filename$, text$ [;]
Append adds a line of text to the end of a file. Unless a semi-colon is at the end of the command, text$ is on a line by itself, otherwise the next append operation on the file adds text$ starting where the last append left off.
Example:
APPEND "visitor.log",date$ + ": "+ remote_host$ REM The above does the same thing as
OPEN "visitor.log" for APPEND AS #1 PRINT #1, date$ + ": "+ remote_host$ CLOSE #1
FILEEXISTS
Syntax: # = FILEEXISTS( filename$ )
Returns -1 if file exists, or 0 otherwize. Example:
if FILEEXISTS("test.log") then ? "test.log file exists"
FILESIZE
Syntax: # = FILESIZE( filename$ )
Returns the number of bytes in the file named filename$, returns -1 if the file does not exist. Example:
n = FILESIZE("test.log")
if n = -1 then print "test.log does not exist." : end
if n = 0 then print "test.log is empty" else print "test.log is",n," bytes"
FILEISLEGAL
Syntax: # = FILEISLEGAL( filename$ )
Returns TRUE (-1) if the passed filename$ is a legal file name, otherwise it returns 0. Example:
if not(FILEISLEGAL(fn$)) then ? "Please enter a valid filename."
FILEISFOLDER
Syntax: # = FILEISFOLDER( filename$ )
Returns TRUE (-1) if the passed filename$ is a folder (directory), otherwise it returns 0. Example:
if not(FILEISFOLDER(dirname$)) then ? "Please enter a directory name."
FILEISREADABLE
Syntax: # = FILEISREADABLE( filename$ )
Returns TRUE (-1) if the passed filename$ is readable, otherwise it returns 0. Example:
if not(FILEISREADABLE(fn$)) then ? "Can't read file:";fn$
FILEISEXECUTABLE
Syntax: # = FILEISEXECUTABLE( filename$ )
Returns TRUE (-1) if the passed filename$ is an executable program, otherwise it returns 0. Example:
if not(FILEISEXECUTABLE(fn$)) then ? "Can't find executable ";fn$
FILEISPROGRAM
Syntax: # = FILEISPROGRAM( filename$ )
Returns TRUE (-1) if the passed filename$ is a program, otherwise it returns 0. It searches the PATH for the program.
Example:
if FILEISPROGRAM(fn$) then ? "Please enter a non-program file."
FILEISWRITEABLE
Syntax: # = FILEISWRITEABLE( filename$ )
Returns TRUE (-1) if the passed filename$ is writeable, otherwise it returns 0. Example:
if not(FILEISWRITEABLE(fn$)) then ? "Can't write to file:";fn$
FILETIMESTAMP
Syntax: # = FILETIMESTAMP( filename$ )
Returns a date variable representing the last modification date of filename$. Example:
n = FILETIMESTAMP("test.log")
print "test.log was lasted changed on:";formatdate$(n,"mm/dd/yyyy") rem print files in current directory
n=files("*","a") for j = 1 to n
print a$(j),filesize(a$(j)),formatdate$(FILETIMESTAMP(a$(j)),"mm/dd/yyyy") next
FREEFILE
Syntax: # = FREEFILE
Returns the next available open file # for use with the OPEN command. Example:
n = FREEFILE
open "myfile" for input as n
COPY
Syntax: COPY sourcefilename$, targetnfilename$
Copies the file named sourcefilename$ to new destination targetfilename$ Example:
COPY "test.txt", "test-copy.txt"
MOVE
Syntax: MOVE sourcefilename$, targetnfilename$
Moves the file named sourcefilename$ to new destination targetfilename$ Example:
COPY "c:\test.txt", "c:\temp\test.txt"
KILL
Syntax: KILL filename$
Deletes the file named filename$ Example:
KILL "test.txt"
RENAME
Syntax: RENAME oldfilename$, newfilename$
Renames a file from oldfilename$ to newfilename$ Example:
RENAME "test.txt", "test2.txt"
LOF
Syntax: # = LOF( filenumber )
Returns the number of bytes in the file associated with filenumber. Example:
open "c:\autoexec.bat" for input as #2 PRINT "Size of file is ",LOF(2)
close
FILES
Syntax: #=FILES(filespec$,arrayname$)
Creates an array of file names in variable arrayname$ matching filespec$ and returns the # of files found. If filespec$ is "", then it matches all files.
Example:
n=FILES("*.xnb","barray")
? n$ + " B FILES"
for j = 1 to n
? j,barray$(j),"
" next
CHDIR
Syntax: CHDIR dirname$
Changes current directory to dirname$ Example:
MKDIR "temp" CHDIR "temp"
MKDIR
Syntax: MKDIR dirname$
Creates a directory named dirname$ Example:
MKDIR "temp"
RMDIR
Syntax: RMDIR dirname$
Removes a directory named dirname$ Example:
RMDIR "temp"
LOCK
Syntax: LOCK filename$
Locks a file named filename$ Example:
LOCK "data.db"
UNLOCK
Syntax: UNLOCK filename$
Unlocks a locked file named filename$ Example:
UNLOCK "data.db"
SQL via SQLite and ODBC
SQLite statements
DBFOR and DBNEXT
DBOPEN [fn$]
DBCLOSE
DBEXEC DBBEGIN DBCOMMIT DBROLLBACK DBCREATE DBDROP DBREINDEX DBALTER DBPRAGMA DBINSERT DBUPDATE DBDELETE DBSELECT
ODBC Commands
SQLCOLUMNS
SQLCONNECT
SQLDISCONNECT
SQLEXEC SQLFOR SQLNEXT
SQLTABLES SQLPRIMARYKEY
SQL statements
xonoBASIC has built-in support for all SQL commands based on the Sqlite database. All xonoBASIC string and numeric functions are supported in SQL statements,ie. select dollar$(23.4)
.
SYNTAX: Enter the SQL statement on ONE line. To use xonoBASIC variables in statements, precede the variable name with a colon.
The SELECT statement not part of a DBFOR statement creates an array of variables corresponding and named after the columns selected in the SELECT statement. The index of the array starts at 1. A variable named sqlrowcount holds the number of rows affected by the last SELECT,UPDATE, OR DELETE statement. Note: because there is a limit on the number of variable created by xonoBASIC, if you query returns more than 20 rows or you have more than 10 columns, you should use the DBFOR command to iterate through your SELECT results.
Example:
ContentTypeHTML
create table test (x int) for j = 1 to 10
insert into test values (:j) next
dbfor rec in select * from test order by 1 desc
? rec.x;"
" dbnext
select sum(x) as thesum,avg(x) as theavg from test
REM NOTE: a SELECT by itself creates variable arrays for each row returned starting with index 1
REM and SQLROWCOUNT holds the # of rows returned.
? thesum(1) ,theavg(1)
DBFOR and DBNEXT
Syntax: DBFOR recordvariable IN selectstatement
The DBFOR command is used to iterate through a record set produced by a SQL SELECT statement. The SELECT statement can be a string also. The block of code starts on the line after the for and until the required DBNEXT command. Selected columns are referenced through the recordvariable followed by a period and then the column name.
Example:
create table test (x int) for j = 1 to 10
insert into test values (:j) next
dbfor rec in select * from test order by 1 desc
? rec.x;"
" dbnext
sql$="select * from test order by 1" dbfor rec in sql$
? rec.x;"
" dbnext
DBOPEN
Syntax: DBOPEN [fn$]
Open or create SQLite database Example:
dbopen 'open memory database
dbopen filename$ 'open a sqlite database file
DBCLOSE
Syntax:DBCLOSE
Close any open sqlite databases Example:
dbclose
DBEXEC
Syntax: dbexec sql$ - run the sql statement contained in sql$ variable.
Run the sql statement in a string variable/constant/expression Example:
sqlexec "create table invoice(invoiceid int, invoicedt date, custid number)" s$="insert into invoice values(1,'2007-11-22',22)"
sqlexec s$
ODBC COMMANDS (The following commands only work with ODBC connections)
SQLCOLUMNS
Syntax: SqlColumns owner$,tablename$
Brings back column information for the table identified by owner$ and tablename$.
The information about columns is stored in array variables and are populated as follows:
Variable Name Description
sqlfieldname$ array variable holding column name
sqlfielddatatype$ "C"-character, "N"-numeric, "D"-date, "T"-time, "TD"-time and date, "B"-bit, "L"-long binary
sqlfieldtype$ this type is the native type, ie. CHAR, NUMBER
sqlfieldprec precision or length of column
sqlfieldscale scale of column
sqlfieldnull 1-nulls allowed, 0-not null
sqlfieldwidth width of column for display purposes.
sqlfieldcomment$ column comment
sqlfieldcount # of columns found
Example: See also SQLTABLES or SQLCONNECT.
SQLCONNECT
Syntax: SqlConnect connect$
Opens an ODBC connection to a database.
The connect$ string consists of one or more of the following:
-Sdata source name
-Uuser name
-Ppassword
-Hhostname (Sql Server)
-duse database name (Sql Server)
-tquery timeout
-llogin timeout
-Rmaximum rows on select statements (ex. -R100)
After a successful connection, sets variable sqlservername$ as the name of the server returned from ODBC.
Example:
rem Connect to Microsoft Access via ODBC sqlconnect "-Saccess"
sqlexec "select * from prospect where prospectid<100 order by prospectid" sqldisconnect
print "Number of Prospects : ", sqlrowcount for j=1 to sqlrowcount
print "ID:";prospectid$(j),"Company:";company$(j) next
REM --
REM -- Connect to Oracle and show tables contenttypehtml
sqlconnect "-SOracle -Usystem -Pmanager" sqltables "","","tv"
? ""
for j=1 to sqltablecount
print "";sqltableowner$(j) print " | ";sqltablename$(j) print " | ";sqltabletype$(j)
next
? " |
"
REM show column names of my_table sqlcolumns "","my_table"
? "
"
print "Column Names for my_table" print string$("-",40)
for j= 1 to sqlfieldcount
print j,sqlfieldname$(j),sqlfieldtype$(j) next
? "
"
sqldisconnect
SQLDISCONNECT
Syntax: SqlDisconnect
Closes the open ODBC connection to a database. Example:
ContentTypeHTML
? ""
rem connect to access database and show prospects sqlconnect "-Saccess"
sqlexec "select * from prospect where prospectid<100 order by Company" sqldisconnect
? ""
print "# | ID Name | Company | Phone" for j=1 to sqlrowcount
? " | ";j;" | ";prospectid$(j);" | ";Company$(j)
? " | ";phonenumber$(j);" |
" next
? "
"
? ""
SQLEXEC
Syntax: SqlExec sql$
Executes a SQL statement (sql$)and sets number of rows affected in variable sqlrowcount. You must use SqlConnect before executing SQL statements. Any valid SQL statement is allowed and executed via the ODBC connection established by SqlConnect. Typical SQL statements are: SELECT, DELETE, INSERT, and UPDATE.
The SELECT statement also creates an array of variables corresponding and named after the columns selected in the SELECT statement. The index of the array starts at 1. A variable named sqlrowcount holds the number of rows affected by the last SQL statement. If a SELECT SQL statement is issued, two additional variables are created that holds the number of fields(columns) and their names. Variable sqlfieldcount holds the number of fields in the last SELECT, and sqlfieldname is an array holding the field names. Note: because there is a limit on the number of variable created by xonoBASIC, you should either limit your query by using an appropriate WHERE clause in the SELECT statement, or use the DIM statement to declare the array variables created by the SELECT statement (ex. DIM firstname$(100)).
Two additional variables are set that identifies the error that may have occurred: sqlerrcode and sqlerrmsg$.
Example: See example in SqlDisconnect.
SQLTABLES
Syntax: SqlTables owner$,tablename$, tabletype$
Brings back a list of tables matching owner$, tablename$, and tabletype$. tabletype$ should be any combination of letters "T"-table, "V"-view, "S"-synonym, "A"-alias, "C"-system catalog.
So to bring back a list of tables and views for owner "BOB", use sqltable "BOB","","TV". The table list consisted of array variables populated as follows:
Variable Name Description
sqltableowner$ array variable holding owner name
sqltablename$ array variable holding table or view name
sqltabletype$ value of "TABLE","VIEW","SYNONYM"
sqltablecount # of tables found
See also SQLCOLUMNS. Example: See SQLCONNECT.
String Commands
CARDINAL$ CENTER$ CHR$ COMMAND$ CRUNCH$ CSV$ DATE$ DOLLAR$
DOUBLEQUOTE$ ENCLOSE$ EXTRACT$ HEX$
INITCAP$ LEFT$ LCASE$ LTRIM$ LPAD$ MID$ OCT$ ORDINAL$ REPLACE$ REVERSE$ RIGHT$ ROMAN$ RPAD$ RTRIM$
SOUNDEX$ STR$ STRING$ SPACE$ TAG$ TIME$ TRIM$ UCASE$ VALUEOF$
These return a number
ASC INSTR LEN MATCH SIMILAR
These are file access related
LOAD$ SAVE$
CARDINAL$
Syntax: $ = Cardinal$(#)
Returns a whole number spelled out in English. See also ORDINAL$. Example:
n=101
print n,Cardinal$(n)
REM returns 101 one hundred and one
CENTER$
Syntax: $ = Center$(S$,len[,c$])
Centers string S$ in a string len character long padding spaces, or c$ if supplied. Example:
Print Center$("I Love You",70) Print Center$("Do You Love Me?",70)
CHR$
Syntax: $ = Chr$(ASCII)
Returns a string one character long whose ASCII value is ASCII. Example:
A$ = Chr$(65)
COMMAND$
Syntax: $ = command$(n)
Returns the nth command line argument as a string, Example:
for j = 1 to 10
if command$(j) <> "" then print j, command$(j) next
CRUNCH$
Syntax: $ = Crunch$(s$,c$)
Replaces multiple occurences of c$ with one c$. Useful in replacing multiple spaces with one space.
Example:
A$ = trim$(crunch$(" this is a test "," "))
CSV$
Syntax: $ = csv$(s$[,sep$][,quotechar$][,escapechar$])
Properly quote a csv string. Example:
sep$ = ","
s$ = "Bill's stuff: toys;books;other"
t$ = "Tom " + quote$ + "Big John" + quote$ + " Walton" print csv$(s$);sep$;csv$(t$)
sep$=";"
print csv$(s$,sep$);sep$;csv$(t$,sep$)
DATE$
Syntax: $ = date$
Returns today's date as a string in the format of MM-DD-YYYY. Example:
print date$,time$
DOLLAR$
Syntax: $ = dollar$(num)
Returns the value of num as a string formatted with a dollar sign, commas, and pennies. 1234.56 would return as $1,234.56
Example:
print dollar$(total)
DOUBLEQUOTE$
Syntax: $ = doublequote(s$)
Returns a string with a double-quote added to the beginning and end of s$. It is the same as: s$ = chr$(34) + s$ + chr$(34) or s$ = quote$ + s$ + quote$. Quote$ is a predefined constant for chr$(34)- the " character.
Example:
print ""
ENCLOSE$
Syntax: $ = enclose(s$,c$)
Returns a string with c$ added to the beginning and end of s$. It is the same as: s$ = c$ + s$ + c$. Example:
sql$="insert into employee (id,name) values ("
sql$ = sql$ + id$ + "," + enclose$(name$,"'") + ")"
EXTRACT$
Syntax: $ = Extract$(dataline$,fieldnum[,delimiter$])
Reads a standard delimited string dataline$ and returns field # fieldnum delimited by a comma, or a character in delimeter$ if specified. Double quotes are removed from a field if enclosed by them. Field numbers start at 1. NOTE: Fields are trimmed of spaces unless the space character is a delimiter character
Example:
data$ = "Hello,Bob,1,2" for j = 1 to 4
print extract$(data$,j) next
data$ = replace$(data$,",","|") data$ = "Hi;" + data$
for j = 1 to 5
print extract$(data$,j,"|;") next
HEX$
Syntax: $ = Hex$(Num)
Returns the string representation of a number in hexadecimal form. The number is changed to an integer for the conversion.
Example:
B$ = Hex$(32)
INITCAP$
Syntax: $ = Initcap$(Str$)
Returns string Str$ with the first letters of each word capitalized and any other letter in small case. Example:
PRINT initcap$(name$)
LEFT$
Syntax: $ = Left$(S$, Length)
Returns a string made up of the left Length characters in S$. Example:
B$ = Left$(A$, 3)
LCASE$
Syntax: $ = LCase$(S$)
Returns S$ in lowercase letters. Example:
B$ = LCase$(A$)
LPAD$
Syntax: $ = LPad$(S$,len[,c$])
Left pads string S$ to len character long with spaces, or c$ if supplied. Example:
Print LPad$("I Love You",70) Print LPad$("Do You Love Me?",70)
LTRIM$
Syntax: $ = LTrim$(S$)
Returns S$ after removing spaces from the beginning of the string. Example:
B$ = LTrim$(A$)
MID$
Syntax: $ = Mid$(S$, Start[, Length])
Returns a string extracted from S$ starting at the 1-based index Start for Length characters. If Length is omitted, the rest of the string from Start is returned.
Example:
B$ = Mid$(A$, 1, 3)
OCT$
Syntax: $ = Oct$(Num)
Returns the string representation of a number in octal form. The number is changed to an integer for the conversion.
Example:
B$ = Oct$(32)
ORDINAL$
Syntax: $ = Ordinal$(#)
Returns a ordinal number spelled out in English. See also CARDINAL$.
Example:
for n=1 to 5
print n,ordinal$(n) next
REM returns 1 first REM 2 second
REM 3 third
REM 4 fourth
REM 5 fifth
REPLACE$
Syntax: $ = Replace$(S$, old$, new$ [,n])
Returns string S$ with old$ replaced with new$. Every occurence of old$ is replaced with new$ unless limited with a 4th argument of n.
Example:
REM replace dog with cat
s$ = Replace$(s$, "dog", "cat")
REM Replace the first occurence of ( with [ s$ = replace$(s$,"(","[",1)
REVERSE$
Syntax: $ = Reverse$(S$)
Returns string S$ in reverse order, ie. reverse$("hello") returns "olleh". Example:
REM reverse s
s$ = Reverse$(s$)
RIGHT$
Syntax: $ = Right$(S$, Length)
Returns a string made up of the right Length characters in S$. Example:
B$ = Right$(A$, 3)
ROMAN$
Syntax: $ = Roman$(n)
Returns the roman numeral string for number n. Example:
for j = 1 to 20 print j,roman$(j) next
RPAD$
Syntax: $ = RPad$(S$,len[,c$])
Right pads string S$ to len character long with spaces, or c$ if supplied. Example:
Print RPad$("I Love You",70) Print RPad$("Do You Love Me?",70)
RTRIM$
Syntax: $ = RTrim$(S$)
Returns S$ after removing any spaces off the end of the string. Example:
B$ = RTrim$(A$)
SOUNDEX$
Syntax: $ = Soundex$(s$)
Returns the soundex value of a string. Example:
if soundex$("Smith") = soundex$("smythe") then print "Match found"
end if
SPACE$
Syntax: $ = Space$(Count)
Returns a string padded with Count number of spaces. Example:
A$ = Space$(32)
STR$
Syntax: $ = Str$(Num[, Width[, Precision]])
Returns the string representation of a number right justified. Width is the minimum of characters (default 1) in the return string. Precision is the number of characters that should appear to the right of the decimal.
Example:
B$ = Str$(1.1, 4, 2)
STRING$
Syntax: $ = String$(Char$, Count#)
Returns a string padded with Count# number of the first character appearing in Char$. Example:
a$ = String$(".", 32)
TAG$
Syntax: $ = Tag$(s$, inchar$, outchar$ [, seperator$])
Returns a string containing all words starting with the inchar$ and ending with the outchar$. Tags can be seperated with an option seperator$ (default is ",")
Example:
a$ = "Text {tag1} with {tag2} tags {tag3}!" print tag$(a$,"{","}","&")
TRIM$
Syntax: $ = Trim$(s$)
Returns s$ after removing leading and trailing spaces. It is the same as ltrim$(rtrim$(s$)). Example:
a$ = trim$(line$)
TIME$
Syntax: $ = time$
Returns the current time as a string in the format of HH24:MI:SS. 9:30 PM would return as 21:30:00.
Example:
print date$,time$
UCASE$
Syntax: $ = UCase$(s$)
Returns s$ in uppercase letters. Example:
a$ = UCase(a$)
VALUEOF$
Syntax: $ = valueof$(varname$[,index])
Returns the string value of the variable named varname$. Example:
total1=1 : total2=10: total3 = 20: s$(5)="Cowboy" for j = 1 to 3
print valueof$("total"+j$) next
print valueof$("s",5)
ASC
Syntax: # = Asc(Char$)
Returns the ASCII value of the first character in Char$. Example:
C = Asc(A$)
INSTR
Syntax: # = instr([startpos,]SrcStr$, SubStr$)
Returns the position (starting at 1) in SrcStr$ where SubStr$ starts. If SubStr$ is not found, returns 0.
Example:
p = Instr( "Where's Waldo?", "Waldo")
LEN
Syntax: # = Len(S$)
Returns the length of S$. Example:
C = Len(A$)
MATCH
Syntax: # = Match(Pattern$,S$)
Returns TRUE (-1) if the regular expression Pattern$ matches string S$.
A match means the entire string TEXT is used up in matching. In the pattern string:
`*' matches any sequence of characters (zero or more)
`?' matches any character
[SET] matches any character in the specified set,
[!SET] or [^SET] matches any character not in the specified set.
A set is composed of characters or ranges; a range looks like character hyphen character (as in 0-9 or A-Z). [0-9a-zA-Z_] is the minimal set of characters allowed in the [..] pattern construct.
Other characters are allowed (ie. 8 bit characters) if your system will support them.
To suppress the special syntactic significance of any of `[]*?!^-\', and match the character exactly, precede it with a `\'.
Example:
REM Validate part # starts with capital letter followed by a digit if not(match("[A-Z][0-9]*",pno$)) then ? "Incorrect part # format"
SIMILAR
Syntax: # = Similar(s1$,S2$)
Returns a number between 0 and 100 indicating how similar 2 strings are. The higher the number, the more similar. This function is case-insensitive.
Example:
REM Compare adjacent lines of text of similarity open "test.dat" for input as #1
while not(eof(1)) j=j+1
line input #1, s$ if j>1 then sim=similar(s$,t$)
if sim > highsim then highsim=sim : highj=j end if
t$=s$ wend close
print "Lines ";highj;" and ";highj-1;" are mostly similar, score=";highsim
LOAD$
Syntax: s$ = LOAD$(filename$ [,"nobom"])
Loads the content of filename$ and stores it in string s$.
"nobom" is an optional parameter that removes any byte order mark from the file without modifying the file itself. Some editors add a BOM what can cause output problems.
Example:
s$ = LOAD$("file.txt")
SAVE$
Syntax: s$ = SAVE$(text$,filename$)
Saves the content of text$ to the file filename$ and also stroes it in s$. Example:
s$ = SAVE$("Felix the cat","file.txt")
Numeric Functions
Math Functions
ABS
ATN
COS
EXP
FIX
LOG
LOG10
MAX
MIN
MOD
ODD
RND
SGN
SIN
SQR
TAN
VAL
Financial Functions
LOANPMT
LOANPCT
LOANTERM
LOANAMT
Nautical Functions
DISTANCE
DEGMINSECTODEC
DECTODEGMINSEC$
ABS
Syntax: # = ABS(Num)
Returns the absolute value of a number. If the number is a negative, it is returned as a positive, otherwise it is simply returned.
Example:
C = Abs(-100)
ATN
Syntax: # = ATN(Num)
Returns the arc tangent of Num. Example:
C = Atn(9)
COS
Syntax: # = Cos(Num)
Returns the cosine of Num#. Example:
C = Cos(9)
EXP
Syntax: # = EXP(Num)
Returns the exponential function of Num. Example:
C = Exp(9)
FIX
Syntax: # = FIX(Num)
Returns the integer portion of a numeric expression value. Example:
REM This will print 1 1 print fix(1.7),int(1.7) REM This will print -1, -2 print fix(-1.7),int(-1.7)
INT
Syntax: # = INT(Num)
Returns the largest integer less than or equal to a numeric expression value. Example:
REM This will print 1 1 print fix(1.7),int(1.7) REM This will print -1, -2 print fix(-1.7),int(-1.7)
LOG
Syntax: # = LOG(Num)
Returns the natural logarithm of Num. Example:
C = Log(9)
LOG10
Syntax:
Returns the base-10 logarithm of Num. Example:
C = Log10(9)
MAX(x,y)
Syntax: # = MAX(x,y)
Returns the maximum value of x and y. Example:
x = max(a,b)
MIN(x,y)
Syntax: # = MIN(x,y)
Returns the minimum value of x and y. Example:
x = min(a,b)
MOD(x,y)
Syntax: # = MOD(x,y)
Returns remainder of x divided by y. Same is x % y. Example:
' Check for multiple of 10 for n = 1 to 100
if mod(n,10) = 0 then print n,"is a multiple of 10" if n % 10 = 0 then print n,"is a multiple of 10" next
ODD
Syntax: # = ODD(n)
Returns a -1 if n is an odd number, 0 otherwise. Example:
for j = 1 to 10
if odd(j) then print j," is odd" next
RND
Syntax: # = RND(Max) or # = Rnd
Returns a random integer from 1 to Max if Max is supplied, or a random number between 0 and 1 if no arguments.
Example 1:
c = rnd(49) ' Generate number between 1 and 49
Example 2:
randomize timer / 3 for i = 1 to 20
num = int(rnd*20) + 1 print num;
next i
SGN
Syntax: # = SGN(n)
Returns a 1 if n is a positive number, -1 if negative, and 0 if zero. Example:
if sgn(j) = -1 then print j," is negative"
SIN
Syntax: # = SIN(Num)
Returns the sine of Num. Example:
C = Sin(9)
TAN
Syntax: # = TAN(Num)
Returns the tangent of Num. Example:
C = Tan(9)
SQR
Syntax: # = SQR(Num)
Returns the square root of Num. Example:
C = Sqr(9)
VAL
Syntax: # = VAL(Num$)
Returns the numerical value of a string. Example:
j = Val("-20")
LOANPMT
Syntax: # = LOANPMT(loanamt,pctrate,mths)
Returns the monthly payment for the percentage rate, loan amount, and # of months in loan. Example:
pmt = loanpmt(100000,6.5,180)
LOANAMT
Syntax: # = LOANAMT(pctrate,payment,mths)
Returns the loan amount for the percentage rate, payment amount, and # of months in loan. Example:
amt = loanamt(6.5,800,180)
LOANPCT
Syntax: # = LOANPCT(loanamt,pmt,mths)
Returns the annual percentage rate for a loan based on the loan amount, payment amount, and # of months in loan.
Example:
pct = loanpct(100000,800,180)
LOANTERM
Syntax: # = LOANTERM(loanamt,pmt,pctrate)
Returns the number of months in a loan based on the loan amount, payment amount, and percentage rate.
Example:
mths = loanterm(100000,800,6.5)
DISTANCE
Syntax: # = DISTANCE(latitude1,longitude1,latitude2,longitude2[,"unit"])
Returns the distance between two geographical points in miles. By setting the optional value "unit" to "n" or "k" returns the distance in nautical miles or kilometers.
Example:
dist = distance(92,207,134,81,"n")
DEGMINSECTODEC
Syntax: # = DEGMINSECTODEC(degrees,minutes,seconds[,"direction"])
Converts degrees, minutes, seconds to a decimal degrees. Direction is optional and can be "n", "s", "w", "e". Default (no direction) is N/E.
Example:
pos = degminsectodec(10,12,8,"s")
DECTODEGMINSEC$
Syntax: # = DECTODEGMINSEC$(decdegrees,longlat)
Converts decimal degrees to degrees, minutes, seconds. The value for longlat can be 0 for latitude or 1 for longitude.
Example:
pos$ = dectodegminsec$(45.55610,0)
Date and Time Commands and Functions
CDATE CTIME
FORMATDATE$ FORMATTIME$ NOW WEEKDAY
CDATE
Syntax: # = CDATE(datestr$)
Returns a number representing the date string datestr$. The datestr$ argument can be in many formats. The function looks for year, month, day first, then month, day, year, then day, month, year. The month portion may be spelled out. Example: n=cdate("Jan 1, 1999").
Example:
PRINT "Here are some dates:" somedate$ = "1998/12/25" dt=cdate(somedate$)
for j = 1 to 10 dt=dt+1
PRINT "Day",j,"is",formatdate$(dt,"mm/dd/yyyy"),"
" next
CTIME
Syntax: # = CTIME(timestr$)
Returns a number representing the time string timestr$. Timestr$ should be in HH MM SS format with optional delimters.
Example:
tv=ctime("15:30")
print formattime$(tv,"hh:mm:ss a")
FORMATDATE$
Syntax: $ = FORMATDATE$(datevar[,fmt])
Returns a string based on fmt for date variable datevar. If fmt is not supplied, then the yyyymmdd format is used.
The possible formats are:
cc century 2 digits, 01-99 y day of year, 1-366
yy year 2 digits, 00-99
yyyy year 4 digits, 100-9999
m month, 1-12
mm month, 01-12
mmm month, 3 letters mmmm month, full name
MMM month, 3 letters, upper case MMMM month, full name, upper case d day, 1-31
dd day, 01-31
ddd day of week, Sun-Sat
dddd day of week, Sunday-Saturday DDD day of week, SUN-SAT
DDDD day of week, SUNDAY-SATURDAY w day of week, 1-7 (1=Sunday)
ww week of year, 1-53 q year quarter, 1-4
\x literal character x other literal character
Example:
PRINT "Today is " + formatdate$(now,"mmmm dd, yyyy")
FORMATTIME$
Syntax: $ = FORMATTIME$(datevar,fmt)
Returns a string based on fmt for date/time variable datevar. The possible formats are:
h hour, 0-23
hh hour, 00-23
m minute, 0-59
mm minute, 00-59
s second, 0-59
ss second, 00-59
c centisecond, 0-99
cc centisecond, 00-99
a a/p indicator - use 12-hour clock
aa am/pm indicator - use 12-hour clock A A/P indicator - use 12-hour clock
AA AM/PM indicator - use 12-hour clock
\x literal character x other literal character
Example:
PRINT "Today is " + formatdate$(now,"mmmm dd, yyyy")
PRINT "The current time is " + formattime$(now,"hh:mm:ss a")
NOW
Syntax: # = NOW
Returns a number representing today's date and time. Example:
PRINT "Now is " + formatdate$(now,"dddd mm/dd/yyyy"),formattime$(now,"hh:mm:ss a")
TIMER
Syntax: # = TIMER
Returns the number of seconds elapsed since midnight. Example:
PRINT TIMER
WEEKDAY
Syntax: # = WEEKDAY(dtvar)
Returns a number 1-7 (Sunday-Saturday) for the day of the week of date datevar. Example:
nums$(1)="first" : nums$(2)="second" : nums$(3)="third"
nums$(4)="fourth" : nums$(5)="fifth" : nums$(6)="sixth":nums$(7)="seventh" PRINT "Today is the " + nums$(weekday(now)) + " day of the week."
Graphics Commands
CAPTCHA
COLOR TABLE
COLOR
CIRCLE
DRAW
IMAGE
LINE
LOCATE
PAINT
PSET
RGB
SCREEN
CAPTCHA
Syntax: CAPTCHA cap$, "[c$]"
Creates a captcha image and stores the solution in a variable. (Image is automatically base64 encoded inline the HTML. Only works with modern browsers)
Captcha code is randomly generated but you can provide your own like: CAPTCHA cap$, "mycode".
Example:
captcha cap$, "" print "
" print cap$
COLOR TABLE
Here are the color numbers used in graphics commands.
Color # Color
0 Black
1 Blue
2 Green
3 Cyan
4 Red
5 Purple
6 Brown
7 White
8 Gray
9 Light Gray
10 Light Green
11 Light Cyan
12 Light Red
13 Light Purple
14 Yellow
15 Bright White
CIRCLE
Syntax: CIRCLE (x,y), radius, [,color][,start[,end]] [,aspect]
Draws a circle centered at (x,y) of radius.
STEP Specifies that coordinates are relative to the current graphics cursor position.
(x ,y ) The coordinates for the center of the circle or ellipse. radius The radius of the circle or ellipse.
color A color attribute that sets the circle's color. start The starting angle for the arc, in radians. end The ending angle for the arc, in radians.
aspect The ratio of the length of the y axis to the length of the x axis, used to draw ellipses.
To convert from degrees to radians, multiply degrees by (PI / 180).
Example:
Circle(100,100),50
COLOR
Syntax:COLOR forecolor[,backcolor]
Sets the foreground color and optionally the backgroud color. Example:
REM Create an image for a counter. const BLUE=1
image 300,20,-1
locate 1,1 color BLUE
print "Hello visitor # ";cnt
DRAW
Syntax: DRAW drawstring$
Draws lines, moves cursor, writes text.
Line-drawing and cursor-movement commands: D[n] Moves cursor down n units.
E[n] Moves cursor up and right n units. F[n] Moves cursor down and right n units. G[n] Moves cursor down and left n units. H[n] Moves cursor up and left n units.
L[n] Moves cursor left n units.
M[{+|-}]x,y Moves cursor to point x,y. If x is preceded by + or -, moves relative to the current point.
R[n] Moves cursor right n units. U[n] Moves cursor up n units.
[B] Optional prefix that moves cursor without drawing.
[N] Optional prefix that draws and returns cursor to its original position.
Color and scale commands:
Cn Sets the drawing color (n is a color attribute). Pn1,n2 Sets the paint fill and border colors of an object (n1 is the fill-color attribute, n2 is the
border-color attribute).
Sn Determines the drawing scale by setting the length of a unit of cursor movement. The default n is 4, which is equivalent to 1 pixel.
Writing Text W[UDRL][n]|text|
Writes a text string to a graphics image at the current coordinate. The string is printed to the right, unless
a direction is specified. U-Up, D-Down, R-Right, L-Left.
If n is specified, the font size increases from 1 to 5. Delimiters must enclose text (|). Ex. DRAW "W3|Hi There!|"
Ex. DRAW "WD3|This goes down!|"
example:
DRAW "U10D50H40L20"
IMAGE
Syntax:
IMAGE [w,h[,c]] [FROM fromfn$] [TO tofn$] [TYPE imagetype$] IMAGE CLOSE
IMAGE CANCEL
This command or SCREEN is necessary before using any of the graphics commands. If creating a new graphic, you must specify the width and height (w,h). You may optionally specify the background color c. If c is -1, then the image background is transparent. If you want to write the graphical image to a file, then specify TO tofn$. You may also read from an existing image file as a starting point by specifying FROM fromfn$. Only one image is active at any one time, so if writing to multiple files using the TO tofn$ option, complete processing on one image before issuing another IMAGE command via IMAGE CLOSE. This command closes the image output file. The TYPE option specified the type of image file. The only current types available are "GIF", "JPEG" and "PNG".
Example:
IF a=1 THEN
IMAGE 400,400,7 TYPE "gif" ELSE
IMAGE FROM "my.gif" END IF
LINE
Syntax: LINE [STEP] (x1,y1) - [STEP] (x2,y2) [,[color] [,B[F]]]
Draws a line from x1,y1 to x2,y2.
STEP Specifies that coordinates are relative to the current graphics cursor position.
(x1,y1), The screen coordinates of the start of the line and of (x2,y2) the end of the line.
color A color attribute that sets the color of the line or rectangle.
B Draws a rectangle instead of a line. BF Draws a filled box.
Example:
Line (100,100) - (200,200)
LOCATE
Syntax: LOCATE row,column
Move the graphics cursor to a row and column. Row starts at 1, column starts at 1. One row equals 16 pixels, one column equals 8 pixels.
Example:
REM Create an image for a counter. image 300,20,-1
locate 1,1
print "Hello visitor # ";cnt
PAINT
Syntax: PAINT [STEP] (x,y) [,[paint] [,[bordercolor]]
Paints a color at position x,y until bordercolor is encountered. Example:
PAINT (100,100),4,7
PSET
Syntax: PSET [STEP] (x1,y1) [,color]
Placing a dot of color at x,y.
STEP Specifies that the x and y are expressed relative to the current graphics cursor location.
(x ,y ) The screen coordinates of the pixel to be set.
color A color attribute that sets the pixel color. If color is omitted, PSET uses the current foreground color.
Example:
for j = 1 to 100 PSET (100,j),1
next
RGB
Syntax: # = RGB (red,green,blue)
Create your own colors based on the entensity of red, green, blue values. This function returns a number to be used in graphics commands requiring a color number. You must use this AFTER the IMAGE command.
Example:
mycolor = rgb(100,50,0) circle (100,100),80,mycolor
SCREEN
Syntax: SCREEN number
This command is given as a convenience for those converting graphics programs from QBasic. It is a substitute for the IMAGE command. The number following SCREEN should be between 1 and 13.
Example:
screen 12
PRINT "Welcome Home!"
Internet and CGI Commands and Functions
CONTENTTYPEHTML CONTENTTYPEIMAGE CONTENTTYPEPLAIN DOCTYPEHTML DOCTYPEXHTML ECHOFILE
EMAIL URLENCODE URLDECODE HTMLENCODE HTMLDECODE HTTPGET HTTPPOST SHOWIMAGE SENDFILE
UPLOADDIROVERRIDE OPENSOCKET / CLOSESOCKET WRITESOCKET / READSOCKET
CONTENTTYPEHTML
Syntax:CONTENTTYPEHTML
Outputs a content type header of text/html. The command is equivalent to
print "Content-type: text/html" print
Example:
ContenttypeHTML
print "Hello World
"
CONTENTTYPEIMAGE
Syntax: CONTENTTYPEIMAGE [imagetype$]
Outputs a content type header of image/jpeg or image/gif. The command is equivalent to
PRINT "Content-type: image/jpeg" PRINT
REM or this if contenttypeimage "gif" PRINT "Content-type: image/gif"
PRINT
Example:
ContenttypeIMAGE "gif" image 100,100
circle (50,50),25
CONTENTTYPEPLAIN
Syntax: ContentTypePlain
Outputs a content type header of text/plain. The command is equivalent to
print "Content-type: text/plain" print
Example:
ContenttypePlain SHELL "dir"
DOCTYPEHTML
Syntax: DocTypeHTML
Outputs a document type header for HTML 4.01 Transitional.
This is important to ensure correct rendering in browsers, like showing tables, links etc. The document type needs to be declared at the very first position of your HTML content.
Example:
ContenttypeHTML DoctypeHTML
DOCTYPEXHTML
Syntax: DocTypeXHTML
Outputs a document type header for XHTML 1.0 Transitional.
This is important to ensure correct rendering in browsers. The document type needs to be declared at the very first position of your HTML content.
Example:
ContenttypeHTML DoctypeXHTML
ECHOFILE
Syntax: ECHOFILE "filename"
Sends a file to the client. Requires headers to be set in order to work correctly. See also SENDFILE
Example:
name$ = "book.pdf"
mime$ = "application/pdf"
print "Content-Type: " + mime$ '---- should default to "application/octet- stream" if not specified.
print "content-disposition: attachment; filename=" + name$ print "Content-Length: ";filesize(name$)
print
ECHOFILE name$
EMAIL
Syntax: EMAIL [TO address$] [FROM address$] [SUBJECT subject$] [ATTACH filename$] [VIA IpOrSiteAddress$] bodyofmessage$
The VIA and TO parts are required. VIA and FROM only need to be identified once. Example:
EMAIL FROM "bill@bill.com" VIA "mail.myisp.com" EMAIL TO "joe@joe.com" SUBJECT "Last Meeting" msg$
Example 2: Mail web form information
REM
REM mailform.xnb - Generic mail form results to someone REM
Contenttypehtml
email via "123.45.67.89" from "myname@mydomain.com" j=1
while (formfield_name$(j) <> "") AND (j<100)
body$ = body$+formfield_name$(j)+" : "+formfield_value$(j)+chr$(13)+chr$(10) j=j+1
wend
email to "myname@mydomain.com" subject "form submission" body$
? "Thank you for the information."
URLENCODE$
Syntax: URLENCODE$(s$)
Performs standard URL encoding on string s$ and returns the encoded string. Example:
print urlencode$("subject=birds nest")
URLDECODE$
Syntax: URLDECODE$(s$)
Performs standard URL decoding on string s$ and returns the decoded string. Example:
print urldecode$("subject=birds+nest")
HTMLENCODE$
Syntax: HTMLENCODE$(s$)
Translates special characters of string s$ into metacharacters and returns the decoded string. Example:
print htmlencode$("")
HTMLDECODE$
Syntax: HTMLDECODE$(s$)
Decode meta characters on string s$ and returns the decoded string. Example:
print htmldecode$("<STRONG>")
HTTPGET$
Syntax: HTTPGET$ hostname$,filename$[,headerarrayname$][,NOHEADER]
Retreives a web page using the HTTP GET method (just like entering an URL in a browser and pressing enter). The results (HTML) are returned in an array named HTTPDATA$. The number of entries in the array is stored in variable HTTPDATACOUNT. HTTPDATA$ also stores the
returning HTTP header information. This header information is separated by an empty entry (representing an empty line or carriage return:chr$(13)) in HTTPDATA$. hostname$ - name of web site host, either an IP address or host name (ie. www.yahoo.com) filename$ - the name of the file to be returned from the host. headerarrayname$ - the name of the array variable holding optional header data to be posted. The array index starts at zero. NOHEADER - optional keyword that specifies that returned header data is not to be stored in httpdata$.
Example:
httpget "www.yahoo.com","/" for j = 1 to httpdatacount
if httpdata$(j) = "" then ok = -1 if ok then print httpdata$(j) next
? "
"
httpget "www.lycos.com","/",NOHEADER for j = 1 to httpdatacount
print httpdata$(j) next
HTTPPOST$
Syntax: HTTPPOST$ hostname$,action$,vararrayname$[,headerarrayname$][,NOHEADER]
Retreives a web page using the HTTP POST method (web forms usually submit data this way). The results (HTML) are returned in an array named HTTPDATA$. The number of entries in the array is stored in variable HTTPDATACOUNT. hostname$ - name of web site host, either an IP address or host name (ie. www.yahoo.com) action$ - this is what is normally specified in the ACTION argument of the FORM tag. varrayname$ - the name of the array variable holding the data to be posted. The data is in name=value format and the array index starts at zero. headerarrayname$ - the name of the array variable holding optional header data to be posted.
NOHEADER - optional keyword that specifies that returned header data is not to be stored in httpdata$.
Example:
httppost "www.mydomain.com","/cal.xnb", "" for j = 1 to httpdatacount
print httpdata$(j) next
SHOWIMAGE
Syntax: SHOWIMAGE (filename$)
Creates a Base64 encoded image inline the HTML. (only works with modern browsers) Example:
SHOWIMAGE ("myimage.jpg")
SENDFILE
Syntax: SENDFILE "filename" [,mimetype] [,header]
Sends a file to the client. See also ECHOFILE Example:
SENDFILE "myfile.jpg","image/jpg","content-disposition: attachment; filename=myfile.jpg"
UPLOADDIROVERRIDE
Syntax: UPLOADDIROVERRIDE ("Folder")
Overrides the default uploaddir settings and sends the uploaded file to the folder specified. If the folder does not exist, it will be created automatically.
Example:
UPLOADDIROVERRIDE("c:\tmp")
SOCKETS
OPENSOCKET / CLOSESOCKET / READSOCKET / WRITESOCKET
commands provide basic support for handling socket connections. Example:
s = opensocket("127.0.0.1",4120)
ret = writesocket(s,"This is a test message!") if ret >= 0 then
ret = readsocket(s) ' data is returned in variable socketdata$ print "socketdata$: ";Socketdata$;"
"
else
print "connection failure" end if
closesocket s
Miscellaneous Commands
DATA / READ / RESTORE
ENCODE$ / DECODE$
END
ENVIRON$
ERASE
$INCLUDE
LBOUND / UBOUND
RANDOMIZE
REM
SHELL$
SLEEP
SPLIT
SWAP
COLON ':'
DATA / READ / RESTORE
Syntax:
DATA var [,var] READ var [,var] RESTORE
DATA stores Static Data anywhere in the Program.
READ reads Static Data from the DATA statements in the program.
RESTORE resets pointer to the first DATA element of the first DATA statement in the program. Example:
'READ string DATA constants in nested loop with RESTORE DIM y, x AS INTEGER
FOR y = 1 TO 2 'data will be printed twice FOR x = 1 TO 5
READ word$ 'input data PRINT x, word$; "
" NEXT x
PRINT : RESTORE 'allow data to be repeated NEXT y
DATA "table", "chair", "book", "desk", "paper" END
ENCODE$ / DECODE$
Syntax:
enc$ = ENCODE$(algorithm$, text$ [,key$]) dec$ = DECODE$(algorithm$, text$ [,key$])
Enables you to ENCODE / DECODE a string.
Encryption and decryption and provided through AES and 3DES. Encrypthion only (hashing) is provided through md5 or SHA1.
Example:
AESenc$ = encode$("aes","ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abc","key")
AESdec$ = decode$("aes",AESenc$,"key")
3DESenc$ = encode$("3des","ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abc","key")
3DESdec$ = decode$("3des",3DESenc$,"key")
MD5enc$ = encode$("md5","ABCDEFGHIJKLabcdefghijkl1234567") SHA1enc$ = encode$("sha1","ABCDEFGHIJKLabcdefghijkl1234567")
END
Syntax: END
END stops execution of the program. Execution also stops without END after the last line of code is executed.
Example:
if s$ = "STOP" then end
ENVIRON$
Syntax: value$ = environ$(name$)
Returns the value of environment variable name$ as a string. Example:
print environ$("PATH")
ERASE
Syntax: ERASE array
Clears a dimensioned array. Example:
dim a$(2) a$(1) = "no1"
a$(2) = "no2" erase a$
print a$(1);a$(2)
$INCLUDE:
Syntax: $INCLUDE: "filename"
Include a file into the source code. The xonoBASIC file is merged into the source code. Example:
REM My program
$INCLUDE: "common.xnb" print "Hello World"
LBOUND / UBOUND:
Syntax: x = LBOUND(array) / x = UBOUND(array)
LBOUND gets the first index of an array. UBOUND gets the last index of an array. Example:
dim a(10)
for i = LBOUND(a) to UBOUND(a) print a(i)
next i
RANDOMIZE
Syntax: randomize seed
Seed the random function (RND) with a new seed. Example:
randomize 100
REM
Syntax: REM followed by anything or nothing
A remark or comment starts on a new line and continues until the next line. You may also use a single quote for a remark.
Example:
REM This is a comment ' And so is this.
SHELL$
Syntax: var$ = SHELL$(cmd$)
Shell executes an external program using the operating system shell. Output is stored in var$.
Example:
print "Results follow:" sh$ = SHELL$("dir")
print sh$ print ""
SLEEP
Syntax: SLEEP n
Suspends execution of program for n milliseconds. NOTE: You normally don't want to slow down CGI programs, use wisely.
Example:
sleep 1
SPLIT
Syntax: # = SPLIT(data$, varname$[,delimiter$])
Split breaks a standard delimited string into pieces. It assigns a variable named varname$ the delimited data in data$. Each field of data$ is assigned to variable varname$ as an array with field 1 assigned to index 1, field 2 to index 2, etc. Index 0 is set to data$. The delimiter for the data is the comma, unless delimiter$ is passed. Delimiter$ may be more than one character. In that case, the field delimiter is one of the characters in delimiter$. The function returns the number of fields in data$.
Example:
REM Read comma delimited file test.csv and print data open "test.csv" for input as #1
if err <> 0 then
print "File test.csv is missing" end ' bail out
end if
20 line input #1, a$
print "==================================================
"
n=split(a$,"b",",") for j = 1 to n
print j,b$(j),"
" next
if eof(1) = 0 then goto 20 close
SWAP
Syntax: SWAP variable1, variable2
SWAP exchanges the values of variable1 and variable2. Since a variable contains both string and numeric values, both types of information is exchanged.
Example:
a=1 b=2
swap a,b
print a,b ' 2,1 swap a,b
print a,b ' 1,2
REM Note that a$,b$ is the same as a,b swap a$,b$
print a$,b$ ' 2,1 for j = 1 to 10
swap varray(j), varray(j+1) next
: (COLON)
Syntax: instruction : instructions
Use the : to line up instructions. Example:
print "hello" : print "world"