Calculator programming and functions

Contents
Mathematics
Numeric handling
Power and exponential functions
Trigonometry
Hyperbolic
Complex mathematic
Summation, multiplication and integration
Probabilities
File access
File information and handling
GUI interface
Dialog building
Button selection window
Information windows
Progress bar
System function
Variable handling
List vars & functions
Execute scripts
System access
Miscellaneous functions
Prime numbers and related functions
Programming
Semicolon ;
Modes
Types
Variables
If statements
Loop statements
Return values

Mathematics

Numeric handling

abs(v) Strip sign (Support complex numbers)
floor(v) Round toward zero
round(v)  Standard 0.5 rounding
sign(v) Return sign, i.e. -1, 0 or 1
limit(value,min,max)  Returns value while between min/max else either min or max.
max(v1,v2,...) Return the highest number from the parameters
min(v1,v2,...) Return the lowest number from the parameters

Power and exponential functions

These functions can handle either real or complex numbers, when argument is complex, result will be complex.

sqr(v) Returns square of v, i.e. v*v
sqrt(v) Returns square root of v
hypot(y,x)  Returns sqrt(sqr(y)+sqr(x))
ln(v) Return natural logarithmic of v
exp(v) Returns e to the v power.
log(v) Return log 10 of v
pow(base,exp)  Returns base to exp power.

Trigonometry

These functions can handle either real or complex numbers, when argument is complex, result will be complex.

acos(v) arc cosine, returns result in radians
asin(v) arc sine, returns result in radians
atan(v) arc tangent, returns result in radians
atan2(y,x) Angle in radians from rectangular coordinates
cos(v) cosine, input is in radians
sin(v) sine, input is in radians
tan(v) tangent, input is in radians
csc(v)  Cosecant, input is in radians
sec(v)  Secant, input is in radians
cot(v)   Cotangent, input is in radians
acsc(v)  arc Cosecant, returns result in radians
asec(v)  arc Secant, returns result in radians
acit(v)  arc Cotangent, returns result in radians

Hyperbolic

These functions can handle either real or complex numbers, when argument is complex, result will be complex.

asinh(v)
acosh(v)
atanh(v)
sinh(v)
cosh(v)
tanh(v)

Complex mathematic

Many functions support complex arguments, they can be entered as real+complex value, i.e. 2+3i or 2+3j (Either i or j can be used to denote a complex number).

cpxPolar(vector,angle) Create a complex value from polar coordinates (Angle is in radians)
conj(v) Calculate the conjugate of a complex value, for sqrt & qeq use this function to show the other complex root.
complex(v) Cast argument to complex

Summation, multiplication and integration

These functions will evaluate a expression argument multiple times to find the result. The supplied expression must be in quotes, i.e. as a string. It is semi-compiled to execute faster.
sum() will sum the result from the expression for each step from start to stop, default stepSize is 1.
sumInt() is the same, but everything is done with integers.
mult() will multiply the results for each step.
integrate() will do a numeric integration, precision usually better then 6 digits and it is fairly slow. If faster speed and less precision is better use the steps argument to limit number of iterations.
deri() calculates the derivative by calculating the slope between a point before and point after the specified x value.
deri2() calculates the second derivative.

sum(expression,start,stop{,stepSize});
sumInt(expression,start,stop{,stepSize});
mult(expression,start,stop{,stepSize});
integrate(expression,start,stop{,steps});
deri(expression,x{,delta});
deri2(expression,x{,delta});

Probabilities

These functions are used for probability and other calculations.

fac() is factorial, it works up to 170.
nCr() combination when taking a sample.
nPr() permutations when taking a sample, this means sequence is relevant.
normD...() All these functions uses the normal distribution curve, the curve can be adjusted with a mean (Default 0) and a sigma (default 1).
V=Value, L=Area of left tail, R=Area of right tail, C=Area of center part, T=Area of both tails,
Lx=x value for area of left tail.
random() Returns a random value between 0 and 1, use parameters to define range (High value is not included).
randomInt() Returns a random value between 0 and max, long value, use parameters to define range (High value is not included).
gRandom() Return a random value with Gaussian distribution (i.e. following the normal distribution curve from above). The value can be anywhere in the double range, but will mostly be within +/- 10 of zero.

fac(n);
nCr(total,sample);
nPr(total,sample);
normDV(x{,mean{,sigma}});
normDL(x{,mean{,sigma}});
normDR(x{,mean{,sigma}});
normDC(x1,x2{,mean{,sigma}});
normDT(x1,x2{,mean{,sigma}});
normDLx(area{,mean{,sigma}});
random();
random(max);
random(min,max);
randomInt();
randomInt(max);
randomInt(min,max);
gRandom()

File access

These functions are designed to write and read text files.
fileAppendText() will create a file (if necessary) and append the parameters to it. Parameters are cast to String before appending. To include a new line use the string "\r\n". Files used with this function will stay open until program terminates or fileAppendClose() is called.
fileReadText() will read a file as one long string, it will secure all lines are terminated with CRLF
fileReadAsArray() will read a text file and return a array with each entry being a line.
fileReadAndParseAsArray() will read a text file in CSV like format and return a array with each entry being a struct with the different elements (The delimeter is used to split elements). The optional fields parameter is a string with the names of each item, when it is missing the file is supposed to start with a line naming the fields.

Code:
```fileAppendText(filename,text,...)
fileAppendClose();
fileAppendClose(filename,...);

```

Binary files works with the bytes data type, both functions handles a file as a single block, i.e. create/open/operation/close in one call.
fileWriteBytes() will cast it parameters to bytes and write them to the file.

Code:
```fileReadBytes(filename);
fileWriteBytes(filename,data,...)
```

File information and handling

File fileInfo() and fileList() both can return a structure with information about the file, it contains: name, fullname, path, type, date, size
The flags used with fileList() are:
• F: List files
• D: List directories
• X or 1-9: Recursive process directories, 1-9 limits how deep, X is without limit.
• A: Instead of a struct return only the absolute path and filename.
• R: Instead of a struct return only the relative path and filename.
• N: Instead of a struct return only the filename.

Code:
```fileExists(filename)
fileInfo(filename);
fileDelete(filename);
```

GUI interface

There are functions to make some simple windows either to show information or to ask for informations.

Dialog building

With these functions a simple input dialog can be build, it must always start with popupInit() and finish with popupShow(), the other functions are used to add input elements.
If the variable varName exists it is used to initialize the value. The variable will be create and fill with the answer when the dialog is accepted with the "Ok" button. The Ok" can be renamed with the popupButton() or popupButtons(), the popupButtons() will also introduce a cancel button
The popupLabel() is only a label and not a input field.
The list is a array type variable with the possible selections.

Code:
```popupInit(title)
popupShow({x,y})
popupNumber(text,varName{,min,max{,tip}})
popupNumberInt(text,varName{,min,max{,tip}})
popupNumberList(text,varName{,min,max{,tip}})
popupNumberIntList(text,varName{,min,max{,tip}})
popupText(text,varName{,maxLength{,tip}})
popupFilename(text,varName{,tip})
popupCombo(text,varName,list{,tip})
popupList(text,varName,list{,lines{,tip}})
popupCheckbox(text,varName{,tip})
popupLabel(text{,varName{,tip}})
popupButton({text{,varName{,tip}}})
popupButtons({text{,varName{,cancelText{,tip}}}})
```

Button selection window

This is a 2 or 3 button window, the answer is always returned, but can also be directly assigned to a variable. Without button names specified the buttons will be "Yes" and "No", the yes button will return 1 and the no button will return 0
The answers are: First button:1, second button:0, third button:2

Code:
```popupShowQuestion(message{,varName{,button1,button2{,button3}}})
```

Information windows

Shows a window with a notification message and optionally a icon (Use 1-4 to select icon).
popupShowInfo() will show the message and wait for the user to press a button.
popupShowInfoAsync() will show the message and let the script continue, if a timeout is specified the window will close after that time, it can at any time be closed by pressing the button.

Code:
```popupShowInfo(message{,icon})
popupShowInfoAsync(message{,icon{,timeout}})
```

Progress bar

Shows a progress bar.
popupShowProgressAsync() shows the window, count is default 100 and timeout is in milliseconds and is default 5 seconds.
popupShowProgressSetPosition() is used to update the bar, it will reset the timeout. If it is used with a value higher than specified count the progress bar is closed.
It is strongly recommended to always specify a timeout value, to avoid a window that stays open if a error appears before the progress bar is full.

Code:
```popupShowProgressAsync(message{,count{,timeout}})
popupShowProgressSetPosition(position)
```

System function

Variable handling

These functions can access variables in some special way.
type will return the actual data type of the variable, clear will clear all contents in the variable (Useful for struct & array), const will mark the variable as read-only, varExists will return if the variable exist or not, clone will make a copy of the variable (With larger variable types (Like struct & array) all vars assigned to it will point to the same value, to avoid this use clone), size will return the length/size of strings, array, vector and bytes.

Code:
```type(var)
clear(var,...)
const(var{,ro})
varExists(varName)
clone(var)
size(var)

var myVar="hello"
type(myVar)
clear(myVar)
const(myVar)
const(myVar,0)
const(myVar,1)
varExists("myVar")
clone(myVar)
size(myVar)
```

List vars & functions

listVars will list the contents of variables, this includes struct and array
getVarList will return a list of all defined variables either on the global or the local level (local is either 0 or 1), in some cases there may be other variables between them that is not listed.
getFuncList will list the name of all defined functions.

Code:
```listVars(var,...)
getVarList(local)
getFuncList()
```

Execute scripts

Execute another script, it is either supplied in a file or as a string. The parameters are accessed as params[index]. It is also possible to define functions, either locally or globally.

Code:
```executeFile(filename{,param1{,param2{,...}}})
executeString(string{,param1{,param2{,...}}})
executeEmbeddedFile(filename{,param1{,param2{,...}}})
executeEmbeddedString(string{,param1{,param2{,...}}})

executeFile("myprogram.txt","hello")
executeString("printConsole(params[0])","hello")
executeEmbeddedFile("myprogram.txt","hello")
executeEmbeddedString("H",20)
```

System access

printConsole output text to system console, executeDos exceute system program, will wait timeout for any console output.

Code:
```printConsole(var,...)
executeDos(program,path,timeout)

printConsole("Starting script")
executeDos("c:\...\pgm.exe,"c:\...,2000)
```

Miscellaneous functions

Prime numbers and related functions

All functions using primes will generate an internal array of primes, making subsequent calls much faster.
primes() returns a array of primes up to max specified, the function can take some time if max is large.
factor() returns a array of primes that multiplied together will give the number.
gcd() greatest common divisor, i.e. the largest number that will divide into all arguments without a remainder.
lcm() least common multiplier, i.e. the smallest number that all arguments  will divide into without a remainder.

Code:
```primes(max)
factor(number)
gcd(number,number,...)
lcm(number,number,...)
```

Programming

In addition to calculations, the calculator also supports programming.

Semicolon ;
It is optional to use a ; between statements, when used the statement will end at the ;, when not used the calculator will determine when the end of a statement is reached.

Modes

The calculator can be invoked in 3 different modes, this is controlled from the program that uses the library. There are execute... functions that makes it possible to break out of a specific mode.
• Expression: Only one expression can be present.
• Execute: The programming mode where any number of statements can be used to make a program.
• Embedded: Process a text with embedded programming. All programming must be between , but it is possible to span statements between them. I.e. H will work and output HHHHHHHHHHH in a string.

Types

long/int
Integer values is a long type that can have up to 19 digits.
In some cases this range can be restricted.
Note: When dividing integer types the result will be a integer, i.e. 1/3 is 0, not 0.333...

double/float
All decimal numbers are handled by a double type that means 15-17 digits precision with a exponent from -324 to 308.
In some cases this range can be restricted.

String
Strings are with double quotes, i.e. "Hello world" and can be added together. They will also be automatic converted to a number (integer or float) if possible when used where a number is expected. The number conversion used on strings are a simple conversion and do not support SI prefix.
It is possible to make long strings by starting and ending with triple double quotes, i.e. """Hello world""", they work exactly the same way as regular strings, but the definitions may stretch over many lines. This also means they will include leading and trailing spaces and any line changes withing the definition.
The string do not have any codepage, but uses unicode, except when typecasting it to bytes where it will use ISO-8859-1 as codepage.
In a string special characters can be inserted with:
• \\: Insert on \
• \": Insert a double quote "
• \': Insert a single quote ' (It do not need to be escaped, but it is allowed)
• \r: Insert a CR character (code 0x0d)
• \n: Insert a LF character (code 0x0a)
• \b: Insert a backspace character (code 0x08)
• \t: Insert a TAB character (code 0x09)
• \xnn: Insert any 8 bit character using the 2 digit hex code
• \unnnn: Insert any 16 bit unicode character using the 4 digit hex code

Bytes
A block of bytes, most variable can be typecase to this type to get the actual bytes. There are some special function to access the bytes in a bytes block.

Complex
A number with a complex component, the complex part of this type is constructed by placing i or j after a number, to get the real part add a regular number to it:
Code:
```3+4j
4-6i
```
When complex number is used with many functions, they will switch to complex mode and may return a complex result.
Code:
```sqrt(-4) is invalid
sqrt(-4+0i) is valid and returns 2j
sqrt(complex(-4)) is valid and returns 2j or 2i
```

Vector
A list of double numbers, there are special mathematical functions for handling this data type. This datatype is constructed with the vector() function.

Matrix

Multiple lines of numbers, there are special mathematical functions for handling this data type. This datatype is constructed with the vector() and matrix() function.

Color
A rgb color, this type is constructed with the color() function.
Code:
```color("red");
color(255,0,0);
```

Datetime
The date and time and also a format. The function date() can be used to construct a datetime value and assign a format to it. In many cases using the formatDateTime() function is better to use that the internal format.

Array
A indexed list of any type variables, this type is created by using [index] on a empty variable or with the array() typecast/function.
First index in a array is always 0 and the size will be expanded up to the highest index used. Each index can be any type, including empty.
Code:
```var a[4];
a[6]="Hello";
a[7]="world";

var b=array(1,2,3);
```

Struct
A named list of any type variables, this type is created by using .name on a empty variable. This type can be used to return multiple values from a function.
Code:
```var a.a=1
a.b=2;
var c;
c.a=10
c.b=20;
```

Variables

Variables can be declared as either local or global, the global type will be present in all instances of the calculator. A variable can be declared multiple times, this is legal and will often happen if a script is run multiple times in the same instance of the calculator.
It is possible to assign a value to a variable when it is declared, this value will be assigned to the variable each time the declaration statement is performed. When no value is assigned a previous declared variable will maintain its already assigned value.
When a value is assigned to a variable it will also assign a type to the variable. When a function or expression requires another type a automatic type conversion is attempted.

Local variable (i.e. var declared) have priority over globally declared variables. If the script is called from another script there may exist variables between global and local from the calling script.

Code:
```var a;
var a=18;

var a,b,c;
var a=1,b=2,c=3;

globalvar a;
globalvar a=18;

globalvar a,b,c;
globalvar a=1,b=2,c=3;
```

If statements

If statements exist in a couple of versions, with simple if, if-else and multiple if-elseif. The elseif must be in one word or a new nested if statement is started.

Code:
```if expression
endif

if expression
else
endif

if expression
elseif expression
elseif expression
else
endif
```

Loop statements

Four types of loops exist in the calculator:
Repeat is used when condition must be tested at end of loop, the loop will always be performed once.
While will test at the start of the loop and may not perform the loop at all.
For will run through the loop a fixed number of times, incrementing or decrementing a variable
foreach will run through each element in a array.

Code:
```repeat statements until expression

while expression do statements endwhile;

var i
for i=startValue to endValue do statements endfor
for i=startValue downto endValue do statements endfor

var a
foreach a in array do statements endforeach
```

All loops can be terminated early with a break statement, this will leave the innermost loop.

Code:
```break;
```

Return values

Depending on usage of the script a return value may be expected or not. There are two ways to define this value:
1) On the last line in the script do something that has a return value:
Code:
```5
sin(3)
a
```
2) Use the "print()" function, this will add to a internal return buffer in the script and can be used anywhere in the script. This will override any last values. This can be used in both execute and embedded mode. In embedded mode any output text will also be added to the internal return buffer.
Code:
```print("Hello ")
print("world")
```