SmallBASIC - Reference guide
Current Version: 0.8.0

>a>>> Useful notes for beginners
_______________________________________________________________________

How to read the syntax:

Everything is written inside of [] characters are optional values.
Everything is written inside of {} characters means you must select one
of them.
The symbol | means OR.
The symbols ... means you can repeat the previous syntax.
The keywords are written with capital letters.

Examples:
Syntax: TEST {1|2}

Valid calls:
TEST 1
TEST 2

Syntax: TEST [HI]

Valid calls:
TEST
TEST HI


>a>>> Limits
_______________________________________________________________________

Bytecode size:                    4 GB
Length of text lines:          4095 characters
User-defined keyword length:     32 characters
Maximum number of parameters:   256
Numeric value range:             64 bit FPN (-/+ 1E+308)
Maximum string size:              2 GB
Number of file handles:         256
Number of array-dimensions:       6
Number of colors:                24 bit (0-15=VGA, <0=RGB)
Background sound queue size:    256 notes
INPUT (console): 1023 characters per call, up to 16 variables
COMMAND$                       1023 bytes

System events are checked every 50ms

=== PalmOS only (or other limited OS):
Length of text lines:           511 characters
Maximum number of parameters:    32
Number of array-dimensions:       3
Maximum string size:            <32 KB
Number of file handles:          16
Number of elements/array:      2970 (that means 64KB of memory)
Bytecode size:                  <64 KB
                      (by using CHAIN you can run progs > 64KB)
INPUT (console): 255 characters per call, up to 16 variables
COMMAND$                        127 bytes

>a>>> Constants and Variables
_______________________________________________________________________

SmallBASIC uses internaly 3 data-types
1. Integer  (32bit)
2. Real     (64bit)
3. String   (<32KB on 16bit / 2GB on 32bit)
4. Array    (~2970 elements on 16bit / ~50M elements on 32bit)

Reals can be also written by using scientific notation.
1E+2, 1E-3, 2.6E-0.25, etc

All user variables (include arrays) are 'VARIANT'. That means the 
data-type is invisible to user.

Variable names can use any alphanumeric characters, extended
characters (ASCII codes 128-255 for non-English languages) the symbol
'_', and the symbol '$'.

The first character of the name cannot be a digit nor a '$'.

About the dollar-symbol:
The symbol '$' is supported for compatibility.
Since in SmallBASIC there is no data-types its use is meanless.

The dollar in function names will be ingnored
The dollar in variable names will be count as part of the name
(that means v and v$ are two different variables)
The dollar in system variables names will be ignore it
(that means COMMAND and COMMAND$ is the same)

abc, a_c, _bc, ab2c, abc$ -> valid names
1cd, a$b, $abc            -> invalid names

Strings may be appended to one another using the + operator.

b = "Hello, " + "world!"

Constant variables can be declared by using the keyword CONST

 CONST ð = 3.14


>a>>> System Variables
_______________________________________________________________________

OSNAME      - Operating System name
OSVER       - Operating System Version (0xAABBCC or 0xABC)
SBVER       - SmallBASIC Version (0xAABBCC)

PI          - 3.14..

XMAX,YMAX   - Graphics display: maximum x (width-1), y (height-1) value
BPP         - Graphics display: bits per pixel (color resolution)

CWD         - Current Working Directory
HOME        - User's directory
COMMAND     - Command-line parameters

TRUE        - The value 1
FALSE       - The value 0


>a>>> Operators (by priority):
_______________________________________________________________________

( )          Parenthesis

+, -         Unary
~            bitwise NOT
NOT or !     Logical NOT  (NOT false = true)

^            Exponentiation

*, /, \      Multiplication, Division, Integer Division
% or MOD     Reminder (like QB's; a=int(a), b=int(b), a-b*(a/b))
MDL          Modulus  (a%b+b*(sgn(a)<>sgn(b)))

+, -         Addition/Concatenation, Subtraction

=            Equal
<> or !=     Not Equal
>,    <      Less Than, Greater Than
=>,   =<     Less or Equal, Greater or Equal
>=,   <=     Less or Equal, Greater or Equal
IN           see "The IN operator"
LIKE         see "The LIKE operator"

AND or &&    Logical AND  
OR  or ||    Logical OR
BAND or &    bitwise AND
BOR  or |    bitwise OR
EQV          bitwise EQV
IMP          bitwise IMP
XOR          bitwise XOR
NAND         bitwise NAND
NOR          bitwise NOR
XNOR         bitwise XNOR


>a>>> Special Characters
_______________________________________________________________________

&h or 0x    Prefix for hexadecimal constant (0x1F,   &h3C)
&o or 0o    Prefix for octal constant       (0o33,   &o33)
&b or 0b    Prefix for binary constant      (0b1010, &b1110)

[,;]        Array definition (function ARRAY())                    ($1)

<<          Appends to an array (command APPEND)                   ($1)

++          Increase a value by 1 (x = x + 1)                      ($1)

--          Decrease a value by 1 (x = x - 1)                      ($1)

p=          Another LET macro (x = x p ...)                        ($1)
            Where p any character of -+/\*^%&|

:           Separates commands typed on the same line

&           Join code lines (if its the last character of the line)
            The result line its must not exceed the max. line size.

#           Meta-command (if its the first character of the line)
            or prefix for file handle

@           The 'at' symbol can by used instead of BYREF          ($1)

'           Remarks

Notes:
($1) = Pseudo operators. These operators are replaced by compiler with
a command or an expression.

>a>>> The OPTION keyword
_______________________________________________________________________

OPTION keyword parameters

This special command is used to pass parameters to the SB-environment.
There are two styles for that, the run-time (like BASE) which can
change the value at run-time, and the complile-time (like PREDEF)
which used only in compile-time and the value cannot be changed
on run-time.

Keyword: BASE (run-time)

    OPTION BASE lower-bound

    Sets the default lower bound for arrays.

Keyword: PREDEF (compile-time)

    OPTION PREDEF {QUITE|COMMAND cmdstr}

    Sets parameters of the compiler

        QUITE
        sets quite flag (-q option)

        COMMAND cmdstr
        sets the COMMAND$ string (usefull for debug reasons)

>a>>> Meta-commands:
_______________________________________________________________________

#!...       
Used by Unix to make source runs as a script executable

#sec:section name
Used internaly to store the section name. DO NOT USE IT!

#inc:"file"
or
#inc:file
Used to include a SmallBASIC source file into the current BASIC code

Example:
...
#inc:"mylib.bas"
...
MyLibProc "Hi"


>a>>> Arrays and Matrices
_______________________________________________________________________

Define a 3x2 matrix

A = [11, 12; 21, 22; 31, 32]

That creates the array

| 11  12 |
| 21  22 | = A
| 31  32 |

The comma used to separate column items; the semi-colon used to 
separate rows. Values between columns can be omitted.

Example:

A = [ ; ; 1, 2 ; 3, 4, 5]

This creates the array

| 0  0  0 |
| 1  2  0 | = A
| 3  4  5 |

Supported operators:

Add/sub:
B = [1, 2; 3, 4]: C = [5, 6; 7, 8]

A = B + C
C = A - B

Equal: 
bool=(A=B)

Unary:
A2 = -A

Multiplication:

A = [1, 2; 3, 4]: B = [5 ; 6]
C = A * B
D = 0.8 * A

Inverse:
A = [ 1, -1, 1; 2, -1, 2; 3, 2, -1]
? INVERSE(A)

Gauss-Jordan:

? "Solve this:"
? "  5x - 2y + 3z = -2"
? " -2x + 7y + 5z =  7"
? "  3x + 5y + 6z =  9"
?
A = [ 5, -2, 3; -2, 7, 5; 3, 5, 6]
B = [ -2; 7; 9]
C = LinEqn(A, B)
? "[x;y;z] = "; C

Note:
There is a problem with 1 dimension arrays, because 1-dim arrays does
not specify how SmallBASIC must see them.

Example:
DIM A(3)

| 1 2 3 | = A

or

| 1 |
| 2 | = A
| 3 |

And because this is not the same thing. (ex. for multiplication)

So the default is columns

DIM A(3) ' or A(1,3)

| 1 2 3 | = A

For vertical arrays you must declare it as 2-dim arrays Nx1

DIM A(3,1)

| 1 |
| 2 | = A
| 3 |


>a>>> Nested arrays
_______________________________________________________________________

Nested arrays are allowed

Example:

A = [[1,2] , [3,4]]
B = [1, 2, 3]
C = [4, 5]
B(2) = C
print B

This will be printed
[1, 2, [4, 5], 3]

You can access them by using a second (or thrid, etc) pair of
parenthesis.

B(2)(1) = 16
print B(2)(1)

Result:
    16


>a>>> The operator IN
_______________________________________________________________________

IN operator is used to compare if the left-expression belongs to 
right-expression

' Using it with arrays
print 1 in [2,3]        :REM FALSE
print 1 in [1,2]        :REM TRUE

' Using it with strings
print "na" in "abcde"   :REM FALSE
print "cd" in "abcde"   :REM TRUE

' Using it with number (true only if left = right)
print 11 in 21          :REM FALSE
print 11 in 11          :REM TRUE

' special case
' auto-convert integers/reals
print 12 in "234567"    :REM FALSE
print 12 in "341256"    :REM TRUE


>a>>> The operator LIKE
_______________________________________________________________________

LIKE is a regular-expression operator.
It is compares the left part of the expression with the pattern (right
part).
Since the original regular expression code is too big (for handhelds),
I use only a subset of it, based on an excellent old stuff by 
J. Kercheval (match.c, public-domain, 1991).
The same code is used for filenames (FILES(), DIRWALK)

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.

To suppress the special syntactic significance of any of `[]*?!^-\',
and match the character exactly, precede it with a `\'.

Examples:

? "Hello" LIKE "*[oO]" : REM TRUE
? "Hello" LIKE "He??o" : REM TRUE
? "Hello" LIKE "hello" : REM FALSE
? "Hello" LIKE "[Hh]*" : REM TRUE

>a>>> The pseudo-operator <<
_______________________________________________________________________

This operator can be used to append elements to an array.

A << 1
A << 2
A << 3

? A(1)


>a>>> Subroutines and Functions
_______________________________________________________________________

SUB name [([BYREF] par1 [, ...[BYREF] parN)]]
  [LOCAL var[, var[, ...]]]
  [EXIT SUB]
  ...
END

FUNC name[([BYREF] par1 [, ...[BYREF] parN)]]
  [LOCAL var[, var[, ...]]]
  [EXIT FUNC]

  name=return-value
END

Use function's name to return the value.

Alternative FUNC/DEF syntax (single-line functions)
This is a macro for compatibility with the BASIC's DEF FN command.

FUNC name[(par1[,...])] = expression
or
DEF name[(par1[,...])] = expression

Example:

DEF FNSin(x) = SIN(x)

? FNSin(pi/2)


Nested procedures/functions are allowed (like Pascal).

Example:

FUNC f(x)
    FUNC f1(x)
        FUNC f2(x)
            f2=cos(x)
        END
        f1 = f2(x)/4
    END

    FUNC f3
        f3=f1(pi/2)
    END

? f1(pi) : REM OK
? f2(pi) : REM ERROR
f = x + f1(pi) + f3 : REM OK
END

The parameters are 'by value' by default.
Passing parameters by value means the executor makes a copy of the
parameter to stack. The value in caller's code will not be changed.

Use BYREF keyword for passing parameters 'by reference'. 
Passing parameters by reference means the executor push the pointer
of variable into the stack. The value in caller's code will be the
changed.

Example:

' Passing 'x' by value
SUB F(x)
  x=1
END

x=2
F x
? x:REM displays 2
____________________________

' Passing 'x' by reference
SUB F(BYREF x)
  x=1
END

x=2
F x
? x:REM displays 1

You can use the symbol '@' instead of BYREF. There is no
difference between @ and BYREF.

SUB F(@x)
  x=1
END

On a multi-section applications sub/funcs needs declaration on the main
section.

Example:
#sec:Main
declare func f(x)

#sec:another section
func f(x)
...
end

Use the LOCAL keyword for local variables.
LOCAL creates variables (dynamic) at routine's code.

Example:

SUB MYPROC
  LOCAL N:REM LOCAL VAR
  N=2
  ? N:REM displays 2
END

N=1:REM GLOBAL VAR
MYPROC
? N:REM displays 1

You can send arrays as parameters.

When using arrays as parameters its better to use them as BYREF;
otherwise their data will be duplicated.

Example:
SUB FBR(BYREF tbl)
  ? FRE(0)
  ...
END

SUB FBV(tbl)
  ? FRE(0)
  ...
END

' MAIN
DIM dt(128)
...
? FRE(0)
FBR dt
? FRE(0)
FBV dt
? FRE(0)

Passing & returing arrays, using local arrays.

Example:

func fill(a)
  local b, i

  dim b(16)
  for i=0 to 16
    b(i)=16-a(i)
  next
  fill=b
end

DIM v(4)
v=fill(v)


>a>>> The pseudo-operators ++, -- and p=
_______________________________________________________________________

The ++ and -- operators are used to increase or decrease the value of a
variable by 1.

Example:

x = 4
x ++ : REM x <- x + 1 = 5
x -- : REM x <- x - 1 = 4

The generic p= operators are used as in C
Where p any character of -+/\*^%&|

x += 4 : REM x <- x + 4
x *= 4 : REM x <- x * 4

All these pseudo-operators are not allowed inside of expressions
y = x ++ ' ERROR
z = (y+=4)+5 ' ALSO ERROR


>a>>> The USE keyword
_______________________________________________________________________

This keyword is used on specific commands to passing a user-defined
expression.

SPLIT s," ",v USE TRIM(x)

In that example, every element of V() will be 'trimmed'.

Use the x variable to specify the parameter of the expression.
If the expression needs more parameter, you can use also the names
y and z


>a>>> The DO keyword
_______________________________________________________________________

This keyword is used to declare signle-line commands.
It can be used with WHILE and FOR-family commands.

Example:

FOR f IN files("*.txt") DO PRINT f

WHILE i < 4 DO i ++

Also, it can be used by IF command (instead of THEN), but is not
suggsted.


>a>>> Uncategorized
_______________________________________________________________________

* White-spaces

The white-spaces in the SmallBASIC and in "C" are:
space, form-feed ('\f'), new-line  ('\n'), carriage-return ('\r'),
horizontal-tab ('\t'), and vertical tab ('\v').

The 'white-spaces' are used by routines like SQUEEZE.

* The '$' is an unused character. You can use it as suffix to
functions names. SB will ignore it.

Example:
x=LEFT("abcd", 2)
y=LEFT$("abcd",2)

Both calls are correct and are the same.

* Notes on FOR-commands

These commands are evaluate the 'destination' everytime.

Example:

FOR i=0 TO LEN(FILES("*.txt"))-1
    PRINT i
NEXT

In that example the 'destination' is the LEN(FILES("*.txt"))-1
For each value of i the destination will be evaluated.
That is WRONG but it is supported by BASIC and many other languages.

So, it is much better to be rewritten as

idest=LEN(FILES("*.txt"))-1
FOR i=0 TO idest
    PRINT i
NEXT

Of course, it is much faster too.

_______________________________________________________________________

>b>>> Commands
_______________________________________________________________________

'|#|REM [remark]

Adds explanatory text to a program listing. 'remark' commentary text,
ignored by BASIC.

The # can be used as remarks only if its in the first character of the
line.

Example:

' That text-line is just a few remarks

REM another comment

# one more comment
_______________________________________________________________________

[LET] var = expr

Assigns the value of an expression to a variable.

var  - A valid variable name.
expr - The value assigned to variable.

Example:
LET x = 4
x = 1               ' Without the LET keyword
z = "String data"   ' Assign string

DIM v(4)
z=v                 ' Assign array (z = clone of v)
_______________________________________________________________________

CONST name = expr

Declares one constant.

name - An identifier that follows the rules for naming BASIC variables.

expr - An expression consisting of literals, with or without operators,
       only. 

Example:

COSNT G = 6.67259E-11
_______________________________________________________________________

DIM var([lower TO] upper [, ...]) [, ...]

Creates an array of (upper-lower)+1 elements.
If the 'lower' is not specified, the arrays are starting from 0

Example: One dimension array of 7 elements, starting from 0

DIM A(6)

Example: One dimension array of 6 elements, starting from 1

DIM A(1 TO 6)

Example: Three dimension array

DIM A(1 TO 6, 1 TO 4, 1 TO 8)

Allocating zero-length arrays:

DIM z()

IF LEN(Z)=0 THE APPEND Z, "The first element"
_______________________________________________________________________

[LABEL] label

Defines a label. There are two kinds of labels. Numeric and 
alphanumeric.

Numeric labels does not needed the keyword LABEL, but alphanumeric
does.

Example:
1000 ? "Hello"

LABEL AlphaLabel: ? "Hello"
...

GOTO 1000
GOTO AlphaLabel
_______________________________________________________________________

GOTO label

Causes program execution to branch to a specified position (label).
_______________________________________________________________________

GOSUB label
.
. [commands]
.
RETURN

Causes program execution to branch to the specified label; when the 
RETURN command is encountered, execution branches to the command 
immediately following the most recent GOSUB command.
_______________________________________________________________________

ON expr GOTO label1 [, ... labelN]
ON expr GOSUB label1 [, ... labelN]

Causes BASIC to branch to one of a list of labels.

expr - A numeric expression in the range 0 to 255. Upon execution of
       the ON...GOTO command (or ON...GOSUB), BASIC branches to the nth
       item in the list of labels that follows the keyword GOTO 
       (or GOSUB).
_______________________________________________________________________

FOR counter = start TO end [STEP incr]
    .
    . [commands]
    .
    . [EXIT FOR]
    .
NEXT

Begins the definition of a FOR/NEXT loop.

counter - A numeric variable to be used as the loop counter. 

start   - A numeric expression; the starting value of counter.

end     - A numeric expression; the ending value of counter.

incr    - A numeric expression; the value by which counter is
          incremented or decremented with each iteration of the loop.
          The default value is +1.

BASIC begins processing of the FOR/NEXT block by setting counter equal
to start. Then, if 'incr' is positive and counter is not greater than
end, the commands between the FOR and the NEXT are executed.

When the NEXT is encountered, counter is increased by 'incr', and the
process is repeated. Execution passes to the command following the NEXT
if counter is greater than end.

If increment is negative, execution of the FOR/NEXT loop is terminated
whenever counter becomes less than end.

FOR/NEXT loops may be nested to any level of complexity, but there
must be a NEXT for each FOR.

Example:

FOR C=1 TO 9
    PRINT C
NEXT

_______________________________________________________________________

FOR element IN array
    .
    . [commands]
    .
    . [EXIT [FOR]]
    .
NEXT

Begins the definition of a FOR/NEXT loop. 

element - A variable to be used as the copy of the current element. 

array   - An array expression

The commands-block will repeated for LEN(array) times. Each time
the 'element' will holds the value of the current element of the array.

FOR/NEXT loops may be nested to any level of complexity, but there
must be a NEXT for each FOR.

Example:

A=[1,2,3]
FOR E IN A
    PRINT E
NEXT

' This is the same with that

A=[1,2,3]
FOR I=LBOUND(A) TO UBOUND(A)
    E=A(I)
    PRINT E
NEXT

_______________________________________________________________________

WHILE expression
    .
    . [commands]
    .
    . [EXIT [LOOP]]
    .
WEND

Begins the definition of a WHILE/WEND loop.

expression - An expression

BASIC starts by evaluating expression. If expression is nonzero (true),
the next command is executed. If expression is zero (false), control
passes to the first command following the next WEND command.

When BASIC encounters the WEND command, it reevaluates the expression
parameter to the most recent WHILE. If that parameter is still nonzero
(true), the process is repeated; otherwise, execution continues at the
next command.

WHILE/WEND loops may be nested to any level of complexity, but there
must be a WEND for each WHILE.

Example:

C=1
WHILE C<10
    PRINT C
    C=C+1
WEND

' This is the same with that

FOR C=1 TO 9
    PRINT C
NEXT
_______________________________________________________________________

REPEAT
    .
    . [commands]
    .
    . [EXIT [LOOP]]
    .
UNTIL expression

Begins the definition of a REPEAT/UNTIL loop.

expression - An expression

BASIC starts executing the commands between the REPEAT and UNTIL
commands. When BASIC encounters the UNTIL command, it evaluates the
expression parameter. If that parameter is zero (false), the process
will be repeated; otherwise, execution continues at the next command.

REPEAT/UNTIL loops may be nested to any level of complexity, but there
must be an UNTIL for each REPEAT.

Example:

Example:

C=1
REPEAT
    PRINT C
    C=C+1
UNTIL C=10

' This is the same with that

FOR C=1 TO 9
    PRINT C
NEXT
_______________________________________________________________________

IF expression1 [THEN]
    .
    . [commands]
    .
[ [ELSEIF | ELIF] expression2 [THEN]
    .
    . [commands]
    .
]
[ELSE
    .
    . [commands]
    .
]
{ ENDIF | FI }

Block-style IF.

Causes BASIC to make a decision based on the value of an expression.

expression - An expression; 0 is equivalent to FALSE, while all
             other values are equivalent to TRUE.

commands   - One or more commands.

Each expression in the IF/ELSEIF construct is tested in order.  
As soon as an expression is found to be TRUE, then its corresponding
commands are executed. If no expressions are TRUE, then the commands
following the ELSE keyword are executed. If ELSE is not specified, then
execution continues with the command following the ENDIF.

IF, ELSE, ELSEIF, and ENDIF must all be the first keywords on their
respective lines.

THEN is optional, but if its defined it must be the last keyword on its
line; if anything other than a comment follows on the same line with
THEN, BASIC thinks it's reading a single-line IF/THEN/ELSE construct.

IF blocks may be nested.

Example:

x=1
IF x=1 THEN
    PRINT "true"
ELSE
    PRINT "false"
ENDIF

' Alternate syntax:

x=1
IF x=1
    PRINT "true"
ELSE
    PRINT "false"
FI
_______________________________________________________________________

IF expression THEN [num-label]|[command] [ELSE [num-label]|[command]]

Single-line IF.

Causes BASIC to make a decision based on the value of an expression.

expression - An expression; 0 is equivalent to FALSE, while all
             other values are equivalent to TRUE.

command    - Any legal command or a numeric label. If a number is
             specified, it is equivalent to a GOTO command with
             the specified numeric-label.

Example:

x=1
IF x=1 THEN PRINT "true" ELSE PRINT "false"
...
IF x=1 THEN 1000
...
1000 PRINT "true"
_______________________________________________________________________

IF(expression,true-value,false-value)

Returns a value based on the value of an expression.

Example:

x=0
PRINT IF(x<>0,"true","false") : REM prints false
_______________________________________________________________________

STOP [error]
or
END [error]

Terminates execution of a program, closes all files opened by the
program, and returns control to the operating system.

error - A numeric expression.

The 'error' is the value which will returned to operating system;
if its not specified the BASIC will return 0.

Note:
  The 'error' value is very well known as ERRORLEVEL value 
  on DOS/Windows systems
_______________________________________________________________________

RESTORE label

Specifies the position of the next data to be read.

label - A valid label.
_______________________________________________________________________

READ var[, var ...]

Assigns values in DATA items to specified variables.

var - Any variable.

Unless a RESTORE command is executed, BASIC moves to the next DATA
item with each READ assignment. If BASIC runs out of DATA items to
READ, an run-time error occurs.

Example:

FOR c=1 TO 6
    READ x
    PRINT x
NEXT

DATA "a,b,c", 2
DATA 3, 4
DATA "fifth", 6

_______________________________________________________________________

DATA constant1 [,constant2]...

Stores one or more constants, of any type, for subsequent access via
READ command.

DATA commands are nonexecutable statements that supply a stream of data
constants for use by READ commands. All the items supplied by all the
DATA commands in a program make up one continuous "string" of
information that is accessed in order by your program's READ commands.

Example:

RESTORE MyDataBlock
FOR I=1 TO 3
    READ v
    PRINT v
NEXT
END

LABEL MyDataBlock
DATA 1,2,3
_______________________________________________________________________

ERASE var[, var[, ... var]]

var - Any variable.

Deallocates the memory used by the specified arrays or variables. 
After that these variables turned to simple integers with zero value.

Example:

DIM x(100)
...
PRINT FRE(0)
ERASE x
PRINT FRE(0)
PRINT x(1):REM ERROR
_______________________________________________________________________

EXIT [FOR|LOOP|SUB|FUNC]

Exits a multiline function definition, a loop, or a subprogram.
By default (if no parameter is specified) exits from last command block
(loop, for-loop or routine).

FOR     - Exit from the last FOR-NEXT loop
LOOP    - Exit from the last WHILE-WEND or REPEAT-UNTIL loop
SUB     - Return from the current routine
FUNC    - Return from the current function
_______________________________________________________________________

LEN(x)

x - Any variable.

If x is a string, returns the length of the string.
If x is an array, returns the number of the elements.
If x is an number, returns the length of the STR(x).
_______________________________________________________________________

EMPTY(x)

x - Any variable.

If x is a string, returns true if the len(x) is 0.
If x is an integer or a real returns true if the x = 0.
If x is an array, returns true if x is a zero-length array (array
without elements).
_______________________________________________________________________

ISARRAY(x)

x - Any variable.

Returns true if the x is an array.
_______________________________________________________________________

ISNUMBER(x)

x - Any variable.

Returns true if the x is a number (or it can be converted to a number)

Example:
? ISNUMBER(12)          :REM true
? ISNUMBER("12")        :REM true
? ISNUMBER("12E+2")     :REM true
? ISNUMBER("abc")       :REM false
? ISNUMBER("1+2")       :REM false
? ISNUMBER("int(2.4)")  :REM false
_______________________________________________________________________

ISSTRING(x)

x - Any variable.

Returns true if the x is a string (and cannot be converted to a number)

Example:
? ISSTRING(12)      :REM false
? ISSTRING("12")    :REM false
? ISSTRING("12E+2") :REM false
? ISSTRING("abc")   :REM true
? ISSTRING("1+2")   :REM true
_______________________________________________________________________

APPEND A, val [, val [, ...]]

A   - An array-variable.

val - Any value or expression

Inserts the values at the end of the specified array.
_______________________________________________________________________

INSERT A, idx, val [, val [, ...]]]

A   - An array-variable.

idx - Position in the array.

val - Any value or expression.

Inserts the values to the specified array at the position idx.
_______________________________________________________________________

DELETE A, idx [, count]

A       - An array-variable.

idx     - Position in the array.

count   - The number of the elements to be deleted.

Deletes 'count' elements at position 'idx' of array A

_______________________________________________________________________

>c>>> System
_______________________________________________________________________

FRE(0|-1|-2|-3)

Returns information about system memory

 0 - free memory
-1 - largest block of integers
-2 - free stack
-3 - largest free block

Unix only:
-10 - total RAM
-11 - used
-12 - free
-13 - shared
-14 - buffers
-15 - cached
_______________________________________________________________________

TICKS() 

Returns the system-ticks. The tick value is depended on operating
system. 
_______________________________________________________________________

TICKSPERSEC()

Returns the number of ticks per second
_______________________________________________________________________

TIMER 

Returns the number of seconds from midnight
_______________________________________________________________________

TIME

Returns the current time as string "HH:MM:SS"

_______________________________________________________________________

DATE 

Returns the current day as string "DD/MM/YYYY"
_______________________________________________________________________

JULIAN(dmy | (d,m,y))

Returns the Julian date.
(dates must be greater than 1/1/100 AD)

Example:

PRINT Julian(DATE)
PRINT Julian(31, 12, 2001)
_______________________________________________________________________

DATEDMY dmy | julian_date, BYREF d, BYREF m, BYREF y

Returns the day, month and the year as integers.
_______________________________________________________________________

WEEKDAY(dmy | (d,m,y) | julian_date)

Returns the day of the week (0 = Sunday)

Example:

PRINT WeekDay(DATE)
PRINT WeekDay(Julian(31, 12, 2001))
PRINT WeekDay(31, 12, 2001)
_______________________________________________________________________

DATEFMT(format, dmy | (d,m,y) | julian_date)

Returns formated date string

Format:
D = one or two digits of Day
DD = 2-digit day
DDD = 3-char day name
DDDD = full day name
M = 1 or 2 digits of month
MM = 2-digit month
MMM = 3-char month name
MMMM = full month name
YY = 2-digit year (2K)
YYYY = 4-digit year

Example:

PRINT DATEFMT("ddd dd, mm/yy", "23/11/2001")

REM prints "Fri 23, 11/01"
_______________________________________________________________________

DELAY ms

Delay for a specified amount of milliseconds.
_______________________________________________________________________

SORT array [USE cmpfunc]

Sorts an array.

The cmpfunc (if its specified) it takes 2 vars to compare. 
cmpfunc must returns
-1 if x < y
+1 if x > y
 0 if x = y

Example:

FUNC qscmp(x,y)
IF x=y 
    qscmp=0
ELIF x>y
    qscmp=1
ELSE
    qscmp=-1
ENDIF
END

DIM A(5)
FOR i=0 TO 5
    A(i)=RND
NEXT
SORT A USE qscmp(x,y)
_______________________________________________________________________

SEARCH A, key, BYREF ridx [USE cmpfunc]

Scans an array for the key.
If key is not found the SEARCH command returns (in ridx) the value 
(LBOUND(A)-1). In default-base arrays that means -1.

The cmpfunc (if its specified) it takes 2 vars to compare. 
It must return 0 if x = y; non-zero if x <> y

Example:

FUNC cmp(x,y)
  cmp=!(x=y)
END

DIM A(5)
FOR i=0 TO 5
    A(i)=5-i
NEXT
SEARCH A, 4, r USE cmp(x,y)
PRINT r:REM prints 1
PRINT A(r): REM prints 4
_______________________________________________________________________

CHAIN file

Transfers control to another SmallBASIC program.

file - A string expression that follows OS file naming conventions;
The file must be a SmallBASIC source code file.

Example:

CHAIN "PROG2.BAS"
_______________________________________________________________________

EXEC file

Transfers control to another program

This routine works like CHAIN with the execption the file can
be any executable file.

EXEC never returns
_______________________________________________________________________

ENVIRON "expr"
or
ENV "expr"

Adds a variable to or deletes a variable from the current environment
variable-table.

expr - A string expression of the form "name=parameter"

If name already exists in the environment table, its current setting is
replaced with the new setting. If name does not exist, the new variable
is added.
_______________________________________________________________________

ENVIRON("var")
or
ENV("var")

Returns the value of a specified entry in the current environment
table.

var  - A string expression of the form "var"
_______________________________________________________________________

RUN cmdstr

Loads a secondary copy of system's shell and, executes an program, or 
an shell command.

cmdstr - Shell's specific command string

After the specified shell command or program terminates, control is
returned to the line following the RUN command.

Notes:
    * PalmOS: The 'cmdstr' is the Creator-ID
    * PalmOS: The RUN never returns
_______________________________________________________________________

RUN("command")

RUN() is the function version of the RUN command. The differnce is
that, the RUN() returns a string with the output of the 'command' as
an array of strings (each text-line is one element).

Notes:
    * PalmOS: The RUN() does not supported.
    * Windows: The stdout and stderr are separated! First is the 
      stdout output and following the stderr.
_______________________________________________________________________

TRON/TROFF

TRACE ON/OFF. When trace mechanism is ON, the SB displays each line 
number as the program is executed
_______________________________________________________________________

LOGPRINT ...

PRINT to SB's logfile. The syntax is the same with the PRINT command.
_______________________________________________________________________

STKDUMP

Displays the SB's internal executor's stack

_______________________________________________________________________

>d>>> Graphics & Sound
_______________________________________________________________________

The SB's Graphics commands are working only with integers.
(Of course, 2D algebra commands are working with reals)
That is different of QB, but its much faster.

The colors
____________________________

Color-mode              Colors

Monochrome              0 = black, 15 = white

2bit (4 colors)         0 = black, 15 = white,  
                        1-6,  8  = dark-gray,
                        7, 9-14 = light-gray

4bit (16 colors)        16 Standard VGA colors
                        16 colors of gray (on PalmOS)

8bit (256 paletted colors)
                        16 Standard VGA colors
                        The rest colors are ignored

15bit (32K colors), 16bit (64K colors) and 24bit (1.7M colors)

         color 0..15 is the standard VGA colors
         full 24-bit RGB colors can be passed by using negative number.


The points
____________________________

Any point can be specified by an array of 2 elements or
by 2 parameters

Example:
LINE x1, y1, x2, y2
or
LINE [x1, y1], [x2, y2]

Also, the polylines can work with the same way.
DIM poly(10)
...
poly[0] = [x, y]


The STEP keyword
____________________________

The STEP keyword calculates the next x,y parameters relative to current
position. That position can be returned by using the POINT(0) and 
POINT(1) functions.


The 'aspect' parameter
____________________________

The x/y factor.


The FILLED keyword
____________________________

The FILLED keyword fills the result of the command with the drawing
color.

_______________________________________________________________________

ARC [STEP] x,y,r,astart,aend [,aspect [,color]] [COLOR color]

Draws an arc

astart,aend = first,last angle in radians.
_______________________________________________________________________

CHART {LINECHART|BARCHART}, array() [, {0|1|2|3} [, x1, y1, x2, y2]]

Draws a chart of array values in the rectangular area x1,y1,x2,y2

type:
0 = simple
1 = with marks
2 = with ruler
3 = with marks & ruler
_______________________________________________________________________

CIRCLE [STEP] x,y,r [,aspect [, color]] [COLOR color] [FILLED]

x,y - the circle's center

r   - the radius

Draws a circle (or an ellipse if the aspect is specified).
_______________________________________________________________________

COLOR foreground-color [, background-color]

Specifies the foreground and background colors 
_______________________________________________________________________

DRAWPOLY array
    [,x-origin,y-origin [, scalef [, color]]] [COLOR color] [FILLED]

Draws a polyline

even elements for x (starting from 0), odd elements for y
_______________________________________________________________________

DRAW string

Draws an object according to instructions specified as a string.

string - A string expression containing commands in the BASIC graphics
definition language.

Graphics Definition Language 

In the movement instructions below, n specifies a distance to move.
The number of pixels moved is equal to n multiplied by the current
scaling factor, which is set by the S command.

  Un    Move up.

  Dn    Move down.

  Ln    Move left.

  Rn    Move right.

  En    Move diagonally up and right.

  Fn    Move diagonally down and right.

  Gn    Move diagonally down and left.

  Hn    Move diagonally up and left.

Mx,y    Move to coordinate x,y. If x is preceded by a + or -, the
        movement is relative to the last point referenced.

   B    A prefix command. Next movement command moves but doesn't
        plot.

   N    A prefix command. Next movement command moves, but returns
        immediately to previous point.

Notes:
    * This command it is had not tested, please report any
      bug or incompatibility.
_______________________________________________________________________

LINE [STEP] x,y [{,|STEP} x2,y2] [, color | COLOR color]

Draws a line
_______________________________________________________________________

PSET [STEP] x,y [, color | COLOR color]

Draw a pixel
_______________________________________________________________________

RECT [STEP] x,y [{,|STEP} x2,y2] [, color | COLOR color] [FILLED]

Draws a rectangular parallelogram
_______________________________________________________________________

TXTW(s), TXTH(s)
or
TEXTWIDTH(s), TEXTHEIGHT(s)

Returns the text width or height of string s in pixels
_______________________________________________________________________

XPOS
YPOS

Returns the current position of the cursor in "characters".
_______________________________________________________________________

POINT(x[,y])

Returns the color of the pixel at x,y

if y does not specified x contains the info-code
0 = returns the current X graphics position
1 = returns the current Y graphics position
_______________________________________________________________________

PAINT [STEP] x, y [,color [,border]]

Fills an enclosed area on the graphics screen with a specific color.

x,y     - Screen coordinate (column, row) within the area that is
          to be filled.

color   - The fill-color

border  - The boundary-color

if the border-color is specified then the PAINT will fill all the
area which is specified by the border-color. 
(fill-until, color!=point(x,y)

if the border-color is NOT specified then the PAINT will fill all
the are with the same color as the pixel at x,y.
(fill-while, color=point(x,y))
_______________________________________________________________________

VIEW [x1,y1,x2,y2 [,color [,border-color]]]

Defines a viewport.

x1,y1,x2,y2     - Corner coordinates of the viewport.
color           - If included, BASIC fills the viewport with the
                  specified color. 
border-color    - If included, BASIC draws a border, in a specified
                  color, around the defined viewport.

The viewport defined by VIEW is disabled by a VIEW command with no 
parameters.
_______________________________________________________________________

WINDOW [x1,y1,x2,y2]

Specifies "world" coordinates for the screen.

x1,y1,x2,y2    The corner coordinates of the world space.

The WINDOW command allows you to redefine the corners of the display
screen as a pair of "world" coordinates.

The world space defined by WINDOW is disabled by a WINDOW command with
no parameters.
_______________________________________________________________________

RGB(r,g,b)
RGBF(r,g,b)

The RGB functions returns the RGB color codes for the specified values

The RGB() takes values 0..255 for each of the color.
The RGBF() takes values 0..1 for each of the color.

The return value is a negative 24bit value to by used by drawing 
functions.
_______________________________________________________________________

BEEP

Generates a beep sound
_______________________________________________________________________

PLAY string

Play musical notes

A-G[-|+|#][nnn][.]      
        Play note A..G
        +|# - sharp
        - - flat
        . - multiplier 1.5

On      - Octave 0..6
        <  - Moves down one octave
        >  - Moves up one octave

Nnn     - Play note 0..84 (0 = pause)
Pnnn    - Pause 1..64
Lnnn    - Length of note 1..64 (1/nnn)
Tnnn    - Tempo 32..255. Number of 1/4 notes per minute.

MS      - Staccato (1/2)
MN      - Normal (3/4)
ML      - Legato

Vnnn    - Volume 0..100

MF      - Play on foreground
MB      - Play on background
_______________________________________________________________________

SOUND freq, dur_ms [, vol]

Plays a sound

freq    - The frequency

dur_ms  - The duration in milliseconds

vol     - The volume in 1/100 units

_______________________________________________________________________

>e>>> Miscellaneous
_______________________________________________________________________

RANDOMIZE [int]

Seeds the random number generator
_______________________________________________________________________

RND

Returns a random number from the range 0 to 1
_______________________________________________________________________

LBOUND(array [, dim])
UBOUND(array [, dim])

Returns the lower/upper bound of the 'array'

The parameter 'dim' is the array dimension whose bound is returned

Example:
DIM v1(-4 TO 7)
DIM v2(1 TO 2, 3 TO 4)

PRINT LBOUND(v1)   : REM -4
PRINT UBOUND(v1)   : REM 7

PRINT LBOUND(v2)   : REM 1
PRINT LBOUND(v2,2) : REM 3
_______________________________________________________________________

CINT(x) - convert x to 32b integer

CREAL(x) or CDBL(x) - convert x to 64b real number
_______________________________________________________________________

PEN ON|OFF

Enables/Disables the PEN/MOUSE mechanism.
_______________________________________________________________________

PEN(0..14)

Returns the PEN/MOUSE data.

Values:
0 - true (non zero) if there is a new pen or mouse event
1 - PEN: last pen-down x; MOUSE: last mouse button down x 
2 - Same as 1 for y 
3 - true if the PEN is down; mouse left-button is pressed
4 - PEN: last/current x, MOUSE: the current x position only if the left
  mouse button is pressed (like PEN is down)
5 - Same as PEN(4) for y 

Mouse buttons (non PalmOS):

10 - current mouse x pos.
11 - current mouse y pos.
12 - true if the left mouse button is pressed
13 - true if the right mouse button is pressed
14 - true if the middle mouse button is pressed
_______________________________________________________________________

PAUSE [secs]

Pauses the execution for a specified length of time, or until user hit
the keyboard.
_______________________________________________________________________

SWAP a, b

Exchanges the values of two variables. The parameters may be variables
of any type.

_______________________________________________________________________

>f>>> File system
_______________________________________________________________________

Special file names:

"COM1:[speed]" - Serial port 1
"COM2:[speed]" - Serial port 2
                 The same for COM3..COM9

"PDOC:filename"
  Compressed PDOC files for PalmOS or PDB/PDOC files on other systems.
  PDOCFS opens and uncompress the file on OPEN; and compress the
  file on CLOSE. So, it will use a lot of memory and time (its depended
  on size of the data).

"MEMO:memo-title"
  MemoDB of PalmOS or regular file on other systems.
  Memo records (virtual files) are limited to 3935 bytes

"SOCL:server:port"
  Socket client. Actually a telnet client.

Example:

OPEN "COM1:" AS #1

OPEN "COM2:38400" AS #2

_______________________________________________________________________

FREEFILE

Returns an unused file handle
_______________________________________________________________________

OPEN file [FOR {INPUT|OUTPUT|APPEND}] AS #fileN

Makes a file or device available for sequential input, sequential
output.

file   - A string expression that follows OS file naming conventions.

fileN  - A file-handle (integer 1 to 256).

FOR -
      INPUT    Sequential input
      OUTPUT   Sequential output
      APPEND   Sequential output, beginning at current EOF

The files are always opened as shared.
_______________________________________________________________________

CLOSE #fileN

Close a file or device
_______________________________________________________________________

TLOAD file, BYREF var [, type]

Loads a text file into array variable.
Each text-line is an array element.

file   - A string expression that follows OS file naming conventions.

var    - Any variable

type   - 0 = load into array (default)
         1 = load into string
_______________________________________________________________________

TSAVE file, var

Writes an array to a text file.
Each array element is a text-line.

file   - A string expression that follows OS file naming conventions.

var    - An array variable or a string variable. Expressions are
         not allowed for memory reasons.
_______________________________________________________________________

EXIST(file)

Returns true if the file exists

file   - A string expression that follows OS file naming conventions.
_______________________________________________________________________

ACCESS(file)

Returns the access rights of the file.

file   - A string expression that follows OS file naming conventions.

The return-value is the permissions of the file as them as specified
on GNU's manual (chmod() and stat() system calls)

The bits (in octal):
04000 set user ID on execution
02000 set group ID on execution
01000 sticky bit
00400 read by owner
00200 write by owner
00100 execute/search by owner
00040 read by group
00020 write by group
00010 execute/search by group
00004 read by others
00002 write by others
00001 execute/search by others

Notes:
    * PalmOS: the return value is always 0777
    * DOS: the return value is depended on DJGPP's stat() function
      Possible, Unix compatible.
    * Windows: the return value is depended on Cygnus's stat() function
      Possible, Unix compatible.

Example:

IF ACCESS("/bin/sh") AND 0o4 THEN
    PRINT "I can read it!"
ENDIF

See also: CHMOD
_______________________________________________________________________

ISFILE(file) - Returns true if the file is a regular file
ISDIR(file)  - Returns true if the filename is a directory
ISLINK(file) - Returns true if the filename is a link

file   - A string expression that follows OS file naming conventions.
_______________________________________________________________________

CHMOD file, mode

Change permissions of a file

file   - A string expression that follows OS file naming conventions.

mode   - The mode is compatible with the chmod()'s 'mode' parameter
         as its described on GNU's manual.
         See ACCESS() for more information.

Examples:

' Make myfile available to anyone (read/write)
CHMOD "myfile.bas", &o666

' Make myfile available to anyone (execute/read/write)
CHMOD "myfile.bas", &o777
_______________________________________________________________________

EOF(fileN)

Returns true if the file pointer is at end of the file.

For COMx and SOCL VFS it returns true if the connection is broken.
_______________________________________________________________________

PRINT #fileN, [USING...] ...

Write string to a file

The syntax is the same with the PRINT command.
_______________________________________________________________________

LINE INPUT [#fileN{,|;}] var
or
LINEINPUT [#fileN{,|;}] var

Reads a whole text line from file or console.
_______________________________________________________________________

INPUT(len[,fileN])

Reads 'len' bytes from file or console (if fileN is omitted).
_______________________________________________________________________

INPUT #fileN; var1 [,delim] [, var2 [,delim]] ...

Reads data from file
_______________________________________________________________________

SEEK #fileN; pos

Sets file position for the next read/write
_______________________________________________________________________

SEEK(fileN)

Returns the current file position
_______________________________________________________________________

LOF(fileN)

Returns the length of file in bytes

For devices; returns the number of available data
_______________________________________________________________________

KILL "file"

Deletes the specified file
_______________________________________________________________________

WRITE #fileN; var1 [, ...]
READ #fileN; var1 [, ...]

The READ/WRITE command set is used to store variables to a file as
binary data.

The common problem with INPUT/PRINT set is there are many conficts with
datas. 

Example:
PRINT #1; "Hello, world"

You have wrote only one string and you want read it in one variable,
but this is impossible for INPUT command to understand it, because
INPUT finds the separator comma, so it thinks there are two variables
not one.

So, now, you can store arrays, strings etc and what is you write is
what you will read the next time.

BTW its faster too.

Notes:
* The parameters can be variables ONLY.
* Its very bad idea to mixed READ/WRITE commands with INPUT/PRINT
  commands in the same file.
_______________________________________________________________________

COPY "file", "newfile"

Makes a copy of specified file to the 'newfile'
_______________________________________________________________________

RENAME "file", "newfile"

Renames the specified file
_______________________________________________________________________

MKDIR dir
CHDIR dir
RMDIR dir

Notes:
Non-PalmOS only.
_______________________________________________________________________

DIRWALK directory [, wildcards] [USE ...]
_______________________________________________________________________

FILES(wildcards)

Returns an array with the filenames.

If there is no files returns an empty array.

Example:

? FILES("*")

Notes: 
* For PalmOS returns only the user-files.
* To use file on MEMO or PDOC or any other virtual file system you must
  use FILES("VFSx:*")

  Example:
  PRINT FILES("MEMO:*")

_______________________________________________________________________

>g>>> Mathematics
_______________________________________________________________________

All angles are in radians.

ABS(x)              - Absolute value of x
COS(x)              - Cosine of x
SIN(x)              - Sine of x
TAN(x)              - Tangent of x
ACOS(x)             - Arc cosine of x
ASIN(x)             - Arc sine of x
ATN(x) or ATAN(x)   - Arc tangent of x
ATAN2(x,y)          - Arc tangent of two variables

Hyperbolic functions:

COSH(x),  SINH(x),  TANH(x)
ACOSH(x), ASINH(x), ATANH(x)

EXP(x)              - the value of e raised to the power of x
LOG(x)              - natural logarithm of x
LOG10(x)            - the base-10 logarithm of x

POW(x,y)            - x raised to power of y
SQR(x)              - square root of x

INT(x)              - rounds x downwards to the nearest integer
FIX(x)              - rounds x upwards to the nearest integer
FLOOR(x)            - largest integer value not greater than x
CEIL(x)             - smallest integral value not less than x
FRAC(x)             - fractional part of x

ROUND(x[,decs])     - rounds the x to the nearest integer or number 
                      with 'decs' decimal digits.

SGN(x)              - sign of x (+1 for positive, -1 for negative
                      and 0 for zero)

DEG(x)              - radians to degrees
RAD(x)              - degrees to radians
_______________________________________________________________________

MAX(...), MIN(...)
ABSMIN(...), ABSMAX(...)

Maximum/Minimum value of parameters. Parameters can be anything 
(arrays, ints, reals, strings).

ABSMIN/ABSMAX returns the absolute min/max value.

Example:
? MAX(3,4,8)
? MIN(array(),2,3)
? MAX("abc","def")
_______________________________________________________________________

SUM(...)                - Sum of value

SUMSQ(...)              - Sum of square value 

STATMEAN(...)           - Arithmetical mean

STATMEANDEV(...)        - Mean deviation

STATSPREADS(...)        - Sample spread

STATSPREADP(...)        - Population spread

Notes:
Sample standard deviation:     SQR(STATSPREADS(array))
Population standard deviation: SQR(STATSPREADP(array))
_______________________________________________________________________

LINEQN(A, B [, toler])

Returns an array with the values of the unknowns.
This function solves equations by using the Gauss-Jordan method.

A = equations
B = results
toler = tolerance number 
    (the absolute value of the lowest acceptable number)
    default = 0 = none

    |x| <= toler : x = 0

Note: The result is a matrix Nx1. For the SB that array is 
      two-dimension array.
_______________________________________________________________________

INVERSE(A)

returns the inverse matrix of A.
_______________________________________________________________________

DETERM(A[, toler])

Determinant of A

toler = tolerance number
  (the absolute value of the lowest acceptable number)
  default = 0 = none

  |x| <= toler : x = 0
_______________________________________________________________________

ROOT low, high, segs, maxerr, BYREF result, BYREF errcode USE expr
_______________________________________________________________________

DERIV x, maxtries, maxerr, BYREF result, BYREF errcode USE expr
_______________________________________________________________________

DIFFEQN x0, y0, xf, maxseg, maxerr, BYREF yf, BYREF er USE expr

Runge-Kutta method

_______________________________________________________________________

>>>>> 2D Algebra
_______________________________________________________________________

SEGCOS(Ax,Ay,Bx,By,Cx,Cy,Dx,Dy)
SEGSIN(Ax,Ay,Bx,By,Cx,Cy,Dx,Dy)

Sinus or cosine of 2 line segments (A->B, C->D).
_______________________________________________________________________

PTDISTSEG(Bx,By,Cx,Cy,Ax,Ay)

Distance of point A from line segment B-C

PTDISTLN(Bx,By,Cx,Cy,Ax,Ay)

Distance of point A from line B, C
_______________________________________________________________________

PTSIGN(Ax,Ay,Bx,By,Qx,Qy)

The sign of point Q from line segment A->B
_______________________________________________________________________

SEGLEN(Ax,Ay,Bx,By)

Length of line segment
_______________________________________________________________________

POLYAREA(poly)

Area of polyline
_______________________________________________________________________

POLYEXT poly(), BYREF xmin, BYREF ymin, BYREF xmax, BYREF ymax

Returns the polyline's extents
_______________________________________________________________________

INTERSECT Ax, Ay, Bx, By,
          Cx, Cy, Dx, Dy,
          BYREF type, BYREF Rx, BYREF Ry

Calculates the intersection of the two line segments A-B and C-D

Returns:
Rx,Ry = cross

type = cross-type
0 = No cross (R = external cross)
1 = One cross
2 = Parallel
3 = Parallel (many crosses)
4 = The cross is one of the line segments edges.
_______________________________________________________________________

2D: 3x3 Matrices

M3IDENT	BYREF m3x3

M3ROTATE BYREF m3x3, angle, x, y

M3SCALE BYREF m3x3, x, y, fx, fy

M3TRANS BYREF m3x3, x, y

M3APPLY m3x3, BYREF poly

Example:

DIM poly(24)
DIM M(2,2)
...

M3IDENT M
M3ROTATE M, pi/2, 0, 0
M3SCALE M, 0, 0, 1.24, 1.24

' Draw the original polyline
DRAWPOLY poly

' Draw the polyline
' rotated by pi/2 from 0,0 and scaled by 1.24 
M3APPLY M, poly
DRAWPOLY poly

_______________________________________________________________________

>h>>> Strings
_______________________________________________________________________

LEN(s)              - length of string
SPC(n)/SPACE(n)     - returns a string of 'n' spaces
BIN(x)              - binary string-value of x
OCT(x)              - octal string-value of x
HEX(x)              - hexadecimal string-value of x
VAL(s)              - numeric value of string s
STR(x)              - convert x to string
ASC(s)              - ASCII code of first character of s
CHR(x)              - returns one-char string of character with
                      ASCII code x
_______________________________________________________________________

LOWER(s), UPPER(s)
or
LCASE(s), UCASE(s)

Converts the string s to lower/upper case

Example:
? LOWER("Hi"):REM hi
? UPPER("Hi"):REM HI
_______________________________________________________________________

LTRIM(s)    - Removes leading white-spaces from string s
RTRIM(s)    - Removes /trailing white-spaces from string s
TRIM(s)     - Removes leading/trailing white-spaces from string s

Example:

? LEN(LTRIM("  Hi")):REM 2

TRIM is equal to LTRIM(RTRIM(s))
_______________________________________________________________________

SQUEEZE(s)

Removes the leading/trailing and duplicated white-spaces

Example:
? "["; SQUEEZE(" Hi  there "); "]"

Result:
[Hi there]
_______________________________________________________________________

ENCLOSE(str[, pair])

Encloses a string.
The default pair is ""

Example:
? enclose("abc", "()")

Result:
(abc)
_______________________________________________________________________

DISCLOSE(str[, pairs [, ignore-pairs]])

Discloses a string.

Default pairs and ignore pairs

First 
non white-space 
character           Check   Ignore
--------------------------------------------
"                   ""      ''
'                   ''      ""
(                   ()      ""''
[                   []      ""''
{                   {}      ""''
<                   <>      ""''

Otherwise:
"                   ""      ''

Example:

s = "abc (abc)"
? s; tab(26); disclose(s, "()")
' prints abc

s = "abc (a(bc))"
? s; tab(26); disclose(s, "()"); tab(40); disclose(disclose(s, "()"), "()")
' prints a(bc), bc

s = "abc (a='(bc)')"
? s; tab(26); disclose(s, "()", "''"); tab(40); &
    disclose(disclose(s, "()", "''"), "()", "''")
' prints a='(bc)', nothing
_______________________________________________________________________

LEFT(s[,n]), RIGHT(s[,n])

Returns the n number of leftmost/rightmost chars of string s
If n is not specified, the SB uses 1
_______________________________________________________________________

LEFTOF(s1,s2),
RIGHTOF(s1,s2)

Returns the left/right part of s1 at the position of the first 
occurrence of the string s2 into string s1

Note: s2 does not included on new string.
_______________________________________________________________________

LEFTOFLAST(s1,s2),
RIGHTOFLAST(s1,s2)

Returns the left/right part of s1 at the position of the last 
occurrence of the string s2 into string s1

Note: s2 does not included on new string.
_______________________________________________________________________

MID(s, start [,length])

Returns the part (length) of the string s starting from 'start'
position

If the 'length' parameter is omitted, MID returns the whole string
from the position 'start'.
_______________________________________________________________________

INSTR([start,] s1, s2)

Returns the position of the first occurrence of the string s2 into
string s1 (starting from the position 'start')

If there is no match, INSTR returns 0
_______________________________________________________________________

RINSTR([start,] s1, s2)

Returns the position of the last occurrence of the string s2 into
string s1 (starting from the position 'start')

If there is no match, RINSTR returns 0
_______________________________________________________________________

REPLACE(source, pos, str [, len])

Writes the 'str' into 'pos' of 'source' and returns the new string.

This function replaces only 'len' characters. The default value of
'len' is the length of 'str'.

Examples:

s="123456"

' Cut
? replace(s,3,"",len(s))

' Replace
? replace(s,2,"bcd")

' Insert
? replace(s,3,"cde",0)

' Replace & insert
? replace(s,2,"RRI",2)
_______________________________________________________________________

TRANSLATE(source, what [, with])

Translates all occurrences of the string 'what' found in the 'source'
with the string 'with' and returns the new string.

Example:

? Translate("Hello world", "o", "O")
' displays: HellO wOrld

_______________________________________________________________________

CHOP(source)

Chops off the last character of the string 'source' and returns 
the result.
_______________________________________________________________________

STRING(len,{ascii|str})

Returns a string that is contains 'len' times of string 'str' or the 
character 'ascii'.
_______________________________________________________________________

FORMAT(format, val)

Returns a formated string.

Numbers:
#       Digit or space

0       Digit or zero

^       Stores a number in exponential format. 
        Unlike QB's USING format this is a place-holder like the #.

.       The position of the decimal point.

,       Separator.

-       Stores minus if the number is negative. 

+       Stores the sign of the number.

Strings:
&       Stores a string expression without reformatting it.

!       Stores only the first character of a string expression.

\  \    Stores only the first n + 2 characters of a string
        expression, where n is the number of spaces between the
        two backslashes. 
        Unlike QB, there can be literals inside the \ \. These
        literals are inserted in the final string.

Example:

? FORMAT("#,##0", 1920.6) : REM prints 1,921
? FORMAT("\  - \", "abcde") : REM prints "abc-de"
_______________________________________________________________________

SPRINT var; [USING...;] ...

Create formated string and storing it to var

The syntax is the same with the PRINT command.

Example:

SPRINT s; 12.34; TAB(12); 11.23;
_______________________________________________________________________

SINPUT src; var [, delim] [,var [, delim]] ...

Splits the string 'src' into variables which are separated by 
delimiters.

Example:

SINPUT "if x>1 then y"; vif, " ", vcond, "then", vdo
? vcond, vdo
' result in monitor
' x>1   y
_______________________________________________________________________

SPLIT string, delimiters, words() [, pairs] [USE expr]

Returns the words of the specified string into array 'words'

Example:

s="/etc/temp/filename.ext"

SPLIT s, "/.", v()
FOR i=0 TO UBOUND(v)
  PRINT i;" [";v(i);"]"
NEXT

displays:
0 []
1 [etc]
2 [temp]
3 [filename]
4 [ext]
_______________________________________________________________________

JOIN words(), delimiters, string

Returns the words of the specified string into array 'words'

Example:

s="/etc/temp/filename.ext"

SPLIT s, "/.", v()
JOIN v(), "/", s
PRINT "[";s;"]"

displays:
[/etc/temp/filename/ext]


_______________________________________________________________________

>i>>> Console
_______________________________________________________________________

Supported console codes

\t		    tab (32 pixels)
\a		    beep
\r\n	    new line (cr/lf)
\xC		    clear screen
\e[K	    clear to EOL
\e[nG	    moves cursor to specified column
\e[0m	    reset all attributes to their defaults
\e[1m	    set bold on
\e[4m	    set underline on
\e[7m	    reverse video
\e[21m	    set bold off
\e[24m	    set underline off
\e[27m	    set reverse off
\e[3nm      set foreground
            color. where n:

            0 black
            1 red
            2 green
            3 brown
            4 blue
            5 magenta
            6 cyan
            7 white

\e[4nm      set background color.
            (see set foreground)

PalmOS only:

\e[8nm	    (n=0..7) select system font
\e[9nm	    (n=0..3) select buildin font
_______________________________________________________________________

PRINT [USING [format];] [expr|str [{,|;} [expr|str]] ...

Displays a text or the value of an expression.


PRINT SEPARATORS
________________

TAB(n)  Moves cursor position to the nth column.
SPC(n)  Prints a number of spaces specified by n.
;       Carriage return/line feed suppressed after printing.
,       Carriage return/line feed suppressed after printing.
        A TAB character is placed.


The PRINT USING
_______________

Print USING, is using the FORMAT() to display numbers and strings.
Unlike the FORMAT, this one can include literals, too.

_       Print next character as a literal. The combination _#, for 
        example, allows you to include a number sign as a literal 
        in your numeric format.

[other] Characters other than the foregoing may be included as
        literals in the format string. 

Notes:
    * When a PRINT USING command is executed, the format will remains
      on the memory until a new format is passed. 
      Calling a PRINT USING without a new format specified, the PRINT
      will use the format of previous call.

Examples:

PRINT USING "##: #,###,##0.00";
FOR i=0 TO 20
    PRINT USING; i+1, A(i)
NEXT

PRINT USING "Total ###,##0 of \ \"; number, "bytes"

Notes:
The symbol ? can be used instead of keyword PRINT
_______________________________________________________________________

CAT(x)

Returns console codes

0  - reset
1  - bold on
-1 - bold off
2  - underline on
-2 - underline off
3  - reverse on
-3 - reverse off

PalmOS only:
80..87 - select system font
90..93 - select custom font

Example:
? cat(1);"Bold";cat(0)
_______________________________________________________________________

INPUT [prompt {,|;}] var[, var [, ...]]

Reads from "keyboard" a text and store it to variable.
_______________________________________________________________________

LINE INPUT var
or
LINEINPUT var

Reads a whole text line from console.
_______________________________________________________________________

INPUT(len[,fileN])

This function is similar to INPUT.

This function is a low-level function. That means does not convert the
data, and does not remove the spaces.
_______________________________________________________________________

INKEY

This function returns the last key-code in keyboard buffer, or
an empty string if there are no keys.

Special key-codes like the function-keys (PC) or the hardare-buttons
(PalmOS) are returned as 2-byte string.

Example:

k=INKEY
IF LEN(k)
  IF LEN(k)=2
    ? "H/W #"+ASC(RIGHT(k,1))
  ELSE
    ? k; " "; ASC(k)
  FI
ELSE
  ? "keyboard buffer is empty"
FI
_______________________________________________________________________

CLS

Clears the screen.
_______________________________________________________________________

AT x,y (in pixels)

Moves the console cursor to the specified position.

x,y are in pixels
_______________________________________________________________________

LOCATE y,x

Moves the console cursor to the specified position.

x,y are in character cells.
_______________________________________________________________________
>->>> SmallBASIC - Reference - EOF
