The Scriptol Programming Language
Common Reference Manual
(c) 2001-2002 by D.G. Sureau
www.scriptol.com
Overview
Scriptol PHP is the first compiler for the new Scriptol programming language.
A compiler producing C++ code is in work, and other will follow.
The goal of the Scriptol language is to be simple, natural and thus to reduce
risk of errors. Scriptol means to "Scriptwriter Oriented Language". It is an
universal language designed to produce dynamic wew pages, scripts and GUI based
applications.
Scriptol may be embedded inside a html page and is converted to the same page
with PHP code, ready for the Net, fully portable.
The language has been defined according to seven rules displayed on the site,
and a page explains also why to use Scriptol.
About this manual
Please note that the [ ] symbols included into syntax of statements are usually
not part of the syntax and denote an optional item, but for indexing and
intervals.
Compiling a Scriptol program
Under Windows, the command is: sol options filename
If the file is compiled, the program is directly launched, else it is compiled
first, and if no error is encountered, it is executed.
While the source has errors, the command "sol filename" compiles it again.
If the source is a html page, it is not executed after compilation.
Under Linux, the command to compile is: solphp options filename
and the command to execute is: php -q filename.php
Options:
none: run a scriptol file, compile it if needed.
-w: compile code embedded inside html page and make a php file.
-4: add the .php4 extension rather than the .php one.
-r: forces to run. Compile if needed, anyway invoques the Php interpreter.
-b: recompile the file and all included ones. Don't run the program.
-v: displays more messages when running a program.
-q: no message after compilation.
Compiling a Scriptol program to native
The command is solc [options] mainfile.
The main file is the one that holds the main() functions. Dependency are
generated by the compiler which knows what to compile or not.
Options:
none: compile only that must be compiled.
-b build all object files.
-c compile all sources into C++ only.
-m make executable.
-r run the executable.
Scriptol project
A Php project is a page with other pages or files included. Scriptol keeps
this structure. A C++ project is a set or sources linked together. Scriptol
combines this structure with the Php one. A Scriptol file must have an "include"
statement for each file the content of which it uses. The compiler generates
either Php pages or a C++ project from the dependencies. No project file is
required.
Scriptol file
A Scriptol file holds a sequence of statements.
The file should have the ".sol" extension, and will be converted into a newer
file with either the ".php" or ".cpp" extension.
In the Scriptol Php version, any kind of statement may be written in a file,
outside the body of function, the whole file is processed as a sequence of
commands.
If compatibility with the C++ version is desired, statements must be written
inside one or more functions, and a "main" function must be defined:
int main()
... statements ...
return 0
main() // starting the script
Scriptol in html page
For Scriptol code embedded inside html, it should be inserted inside the
following tags:
or
or 'scriptol' or "scriptol"
The "script" keyword may be required by some html editors.
The last line of a Scriptol script must be terminated by a semi colon or an end
of line, before the ?> symbol.
The simplest way to use a Scriptol script is to call it from a Php page, that
holds a simple include statement:
Ex:
This example calls a Php counter inside the count.php file, built from the
count.sol file with the command: sol -web count.sol
(See at www.scriptol.net).
Statement
A statement is ended by a semi-colon or by the end of the line.
When a statement exceeds the width of a line, the line is concatened with the
following one providing that it is ended by a comma, or by an operator. The '\'
symbol is not used by Scriptol.
Multiple statements on a same line are separated by a semi-colon. This is
provided mostly to leave freedom to programmers, but may be useful if you
insert Scriptol code into an html page and the editor concatenates the lines!
Comment
A single line comment start with ` and ends with the end of line.
The // symbol is allowed also.
A multi-lines comment starts with /* and ends with */.
Symbols
The Scriptol language does not use same symbols for conceptually different
usages.
The ";" sign is a end of statement terminator.
The "," is a separator. It separates elements of an initializer, or of a tuple.
The ":" sign builds an association. It attaches a body to a header, a value to
a key, a method to an object, and so one...
The "." sign uses an association. It associates a method call to the object.
The ".." and "--" are interval symbols. They separate the limits of an interval
of two numbers, for indexing or scanning.
() are grouping symbols. They group sub-expressions, or elements of an array.
[] are indexing symbols. They denote an index or an interval.
"?" is a question mark as in natural language. It terminates a condition in
one-line control structures.
Apart the usual arithmetical operators, the language uses "<>" as a "not equal"
operator (or "!=").
"&" , "|", "<<" are standard binary operators.
"#" is the list intersection operator.
"||" is the list union operator.
Boolean operators are "and", "or", "not".
:= is the operator of conditional assignment (see at level 2 manual).
Identifiers and keywords
Identifiers are name of variables or functions.
They are not case-sensitive, you can't give same name to two different objects,
one in uppercase and the other in lowercase.
Keywords are reserved words of the language and are lowercase.
All that is transmitted to the target language must not to make difference
with case.
Variable or primitives
Variables are basic objects. When used as arguments of a function, the function
uses a copy of them, and doesn't modify the original.
Instances of classes, are not copies in arguments of function, the arguments
are just different names for the original objects.
Scriptol Php's primitives are these:
number any king of number.
integer a rounded number to integer part.
int equivalent to integer.
real a number with decimals.
boolean the true or false value.
text a string of characters.
array an indexed and dynamic list of objects
dict an associative list of pairs key:value.
Other special types exist:
dyn generic element of array or value of dict.
file a file handler.
function a var which may be used as a function.
When converted to Php, all variables become dynamic and are prefixed by $. But
the type is required by the Scriptol compiler to perform right tranformations.
Declaration
The declaration of a variable has the form:
type var
Ex: int x
Multiple declaration is allowed in the form:
type name = value, name = value, ...
Ex: int x = 0, y = 0
This form is not allowed: int x, y = 0, 0
Constant
The constant modifier defines a variable whose value can't change.
Ex:
constant integer x = 5 // you can't assign to x another value.
There are predefined constants in the langage:
true matches an expression that is true.
false the opposite.
zero the 0 value.
nil object not found inside a sequence (Not In List).
null value of an object while not initialized yet.
Extern, external variables, constants and function
Php variables and constant may be used as scriptol objects, providing they
are declared with the extern keywords.
"extern", as "include" must be put at start of a source file.
The syntax is:
extern type identifier
extern constant type identifier
It is possible also to use a Php variable directly with the $ prefix.
In this case, no test is performed on the type and the scope, and you must
use a global statement if you use them inside a function.
Ex:
global argv
array a = $argv
The syntax for a native Php constant is: $(constant_name)
The syntax to declare a Php function is:
extern type identifier(... arguments...)
In each argument, the type is required, but the identifier may be omitted.
A default value is denoted by an assignment.
Ex:
extern text substr(text, int, int x = 0)
The identifier x and the value have no importance.
Assignment
The syntax of a simple assignment is:
identifier = expression
Scriptol allows to simplify arithmetical operations on a variable when the
result is assigned to the same variable.
The syntax of such an augmented assignment is:
identifier operator expression
Augmented operators are: + - * / mod << >> | & ^ # ||
Ex: a = 1 // give a the value 1
Ex: a + 1 // add 1 to a
Ex: a * (x + 2) // multiply a by the expression
Ex: a = a * (x + 2) // similar to above
The corresponding Php or C++ statements are:
a = 1;
a += 1;
a *= x + 1;
a = a * (x + 2)
Multiple assignments
Ex: x, y, z = 1, x2, 8
The number of expressions at right must either match the number of targets
at left or may be a single value assigned to several variables.
Ex: x, y, z = 0
The multiple assignment allows a function to return several values.
The complete rule
You may assign several variables together from:
- a value or expression.
- an array.
- values of a dict (use the values() method).
- a function's call.
- a tuple of values or expressions separated by commas.
In the case of array or dict, of a tuple, or a function returning several
values, the variables from 1 to n are assigned the items from 1 to n, in the
same order. If the number doesn't match, it is an error.
If the function returns a single value, the same value is assigned to all
variables at left.
Reversing assignment
If we can assign several variables from the content of an array, we can also
create an array with the content of variables:
array a = (varname1, varname2, etc...)
Conditional assignment
This special assignment is intended to change a property or other variable
that has already a default value, when a new value is given.
The := symbol assign conditionally a variable, if the expression is not
nil or if the variable is not initialized.
The error flag is set to false if the expression to assign is nil.
Example:
int x := z
error ? print "z is nil"
The above assignment is equivalent to:
if (x = null) or (z <> nil) ? x = z
Only simple assignments may be conditional and use the := symbol.
Operators
Comparison operators are: = < > <= >=
There are two operators to test difference: != and <>
The "in" operator tests the inclusion of an element in a sequence:
a string in a text, an object in an array, a value in a range.
Ex: if "a" in line ? print "in text"
Ex: if x in 1..10 ? print "in range"
Binary operators are:
& (and) | (or) ^ (exclusive or) ~ (not) << (shift left) >> (shift right).
Precedence
Unary operator have precedence over binary ones. Among binary operators,
precedence must be denoted by parenthesis.
Expression
An expression is a combination of value and operators.
A conditional expression is a set of two at least expressions linked by
relational operators (=, <, >, etc...) and returns a boolean value.
A binary expression is a set of numbers linked by binary operators (| & ~) and
it returns the type of the first value.
Function
A function starts with a header and ends with the "return" keyword.
The header has the form:
return-type [, return-type]* identifier ( parameters )
Ex: int myfunc(int x)
Ex: int, boolean myfunc(text t, int i)
The return type is required and the type of arguments also. You can use
"void" if the function return nothing.
A parameter may have a default value and can then be omitted.
Ex: void myfunc(text a = "demo")
call: myfunc() or myfunc(some-text)
The body is a list of statements, including some "return" if needed.
The ending statement is a return with zero, one, or several values.
Ex: return
Ex: return x
Ex: return x, y, 5
A call to a function may assign zero, one, or several variables.
Ex: myfunc()
Ex: a = myfunc()
Ex: a,b,c = myfunc()
Arguments of a function: the alias modifier
When a function has object as arguments, the name of the arguments are aliases
of the original objects, and any change inside the function are made in fact
on the original objects.
By default, primitives are copy and other arguments are aliases.
You can change the defaults with a modifier:
"alias": the name of the primitive becomes an alias of the original.
Ex:
void func(number x)
x + 1
print x
return
void funcalias(alias number x)
x + 1
print x
return
number y = 5
func(y)
print y
>>> should display 6 then 5
funcalias(y)
print y
>>> should display 6 then 6.
The "main" function
It is often required to pass arguments to a program from the command line.
To do that in Scriptol (as in Php), use the external $argv Php variable.
To mimic the way C++ passes arguments to a program, declare a function "main",
and call it with $argv (and $argc if needed) as argument.
extern int argc
extern array argv
int main(int argnum, array arglist)
print argnum, "arguments"
scan arglist
print arglist[]
/scan
return 0
main($argc, $argv) ` argc and argv are external Php variables.
The main function may be declared either as above or without argument:
int main()
int main(int, array)
Using a variable as a function
A variable declared with the type "function" may by used as a function.
Example:
void myfunc(int a, int b)
print a, b
return
function f = "myfunc"
f(10, 20)
>>> should display: 10, 20
This doesn't work inside a class. This allows to pass a function as argument
of another one, and thus, to perform different processing with a same algorithm.
Print and echo
Print
Syntax: print expression [, expression]
Displays a formatted text.
Each comma results in a white space, and a newline is sent after the text.
Ex: print "demo", 5
>>> display: demo 5
A single print statement, without argument, send a line feed.
Ex: print
Echo
Syntax: echo expression [, expression]
Displays a text as is.
There is no white space between expressions nor line feed at end.
Ex: echo "demo", 5
echo "next"
>>> display: demo5next
The string following the print or echo statement is transmitted to php as is.
If it contains the $ sign, that is a variable for the php interpreter.
Ex:
a = 10
echo "score $a"
>>> this displays: score 10.
Warning!: One can put a variable inside a text with the $ prefix, but inside a
method of a class, one must not do that for an attribute of the class, as the
compiler must perform a translation.
Control structures
The control structures are:
if
normal if.
one-instruction if.
composite if.
for
normal for.
one-instruction for.
- options: in interval, in array.
scan
by function.
one-instruction scan.
tag scan.
while
normal while.
one-instruction while.
- options: let, forever.
do while
normal.
case / else / always.
- option: forever.
do until
enum
simple enum.
dict enum.
Scriptol has different syntaxes for single instruction and multi-lines control
structures.
A one-instruction control structure has the form:
structure-keyword expression let statement
or structure-keyword expression ? statement
"Let" means for "Last statement, Execute, Terminate". The let element is always
the last part of a control structure and may be the single one. The "?" symbol
is just a shorter replacement for "let".
In this case there is no ending but the end of line. A semi-colon, if present
after the statement, terminates the whole construct instead.
The statement may be any basic statement and can't be a control structure.
If "else" or "let" completes the control structure on the same line, the
statement and "else" or "let", must be separated by a semicolon.
A multi-lines control structure has the form:
structure-name expression [:]
... statements ...
/structure-name
The colon is optional (but if a statement is put on the same ligne).
Here all statements may be embedded. Each statement is ended either by the end
of line or a semicolon.
The if construct
One-instruction
Syntax:
if boolean condition ? statement
[else statement]
or: if condition ? statement ; else statement
One must read the line as this:
is condition true? if yes, action...
Ex: if a = 5 ? break
Ex: if a < 5 ? print "less"
else print "more/equal"
Ex: if a = 1 ? print "1"; else print "?"
Multi-lines
Syntax:
if boolean condition [:]
... statements ...
else // optional
... statements ... //
/if
N.B.: The colon is optional after the condition, as the semi-colon after a
statement, but is required to concatenate the lines.
Ex:
if (x + y) > 8
print "> 8"
else
print "<= 8"
/if
Ex: if a = 5 : a + 3 ; print a ; else print "not 5"; /if
The composite if control structure
The switch case construct of C++ or Java is not implemented in Scriptol because
it is too weak and useless.
It is replaced by a more powerful variant of the if construct, that can match
any type of variable, and various types of comparisons.
The syntax is:
if not-boolean expression [:]
operator expression : statements
operator expression : statements
...
else
... statements ...
/if
A not-boolean expression, is an ident, a litteral, or any expression that
doesn't return a boolean value (true or false).
There are no "break" keyword after a case group. A break will causes exiting
from the control structure that would hold the "if".
The valid operators are:
=, <, >, <=, >=, !=, <>, in, match.
The "else" here is equivalent to "default" in the switch case of C.
Ex:
if a
= 1: print 1
= 2: print 2
> 2: print ">2"
else print "<1"
/if
The for control structure
This control structure scans either a range or a sequence and puts each item
in a variable.
Syntax:
for variable in start..end [step s] [:]
... statements ...
/for
Start, end, step are either identifiers or constants.
The step is optional, the default value is 1.
The end value is included in the range.
The end value may be inferior to the start one, providing the step is present.
- if they are variables, the step must be a (negative) literal integer.
- if they are literal integers, the step may be a variable.
The container variable may be declared into the heading, in this case, it is
local to the control structure.
Syntax:
for variable in array-expression [:]
... statements ...
/for
In this case, the content of an expression is scanned and each item assigned
to the variable. The expression must be an array or any expression that returns
an array.
Ex: for i in 1..10
print i
/for
Ex: for w in myarray
print w
/for
Ex: for w in arr1 + (arr2 # arr3[0..5])
print w
/for
One-instruction for
The one-instruction shortened syntax is:
for ident in list let basic-statement
Ex: for w in mylist let print w
Ex: for x in 10..1 step -1 let print w + 10
The scan construct
This is a simplified form of the for construct with arrays.
Syntax:
scan a [,b, etc...] by f
- a, b, etc... are arrays.
- f is the name of a function.
This applies the function to each item of the arrays providing that the
function has as many arguments as there are arrays.
For the function to modify the array, the "alias" modifier must be put before
the type of the argument.
Scan by requires a user function, and not a method of class.
Warning: Indexes of an array are not the positions inside the array: a[1] may
return a value that has not the position 1 in the array (see Array).
Other syntax:
scan a
... statements ...
/scan
In this form, each item of the array(s) is(are) processed by the statements
inside the body of the constuct. The current item is accessed with the [] empty
indexing.
The one-instruction syntax is also allowed:
scan a ? statement
Ex:
array a = (1,2,3,4)
void fun(number x) : print x * x; return
scan a by fun
Ex:
scan a : print a[] * a[]; /scan
These two examples have the same result.
One can modify the array by an assignment as: a[] = ...
Ex:
scan a let a[] = 0
Ex:
scan a
a[] * a[]
print a[]
/scan
Example with several arrays:
void mulfun(dyn a, dyn b) print a * b; return
scan a,b by mulfun
or: scan a,b let print a[] * b[]
The while control structure
One-instruction
while expression let instruction
Multi-lines
while expression [:]
... statements ...
/while
A "break" statement exits the loop.
A "continue" statement skip all that follows and starts a new loop.
The Php equivalent is:
while (expression)
{ statements }
The while let option
This syntax is recommended to avoid the risk of infinite loops.
The assignment that do the tested expression evolves, may be moved after the
/while by the mean of the "let" statement.
Ex:
while x < 10
print x
/while let x + 1
The Php equivalent (not the generated one) is:
while (x < 10) {
print x
x += 1
}
However, the "continue" statement has not the same effect, it jumps to the
incrementor (x + 1) in Scriptol, while it starts a new loop in the standard Php
control structure (not the generated one).
Simplified syntax
A while with the let option may be written simply as:
while condition
...statements...
let incrementor
In the case of one-statement loop, the : operator must be used if the let
is used also.
Ex: while x < 10 let x + 1
Ex: while x < 10 : print x; let x + 1
In the first example, any statement may follow the let. In the second one,
let must be followed by an assignment.
The forever option
The condition may be is replaced by the "forever" keyword, and we enter an
infinite loop, exited by a "break".
The do while construct
The block of statements is performed while the condition is true.
Syntax:
do
... statements ...
/do while expression
Ex:
do
print x
x + 1
/do while x < 3
Options
- do ... /do without while is valid and useful with case groups.
- do ... /do forever
performs an infinite loop, and requires a break to exit.
The do case construct
This is a powerful pattern-matching control structure. It contains one or
several case groups followed by an optional else and an optional always.
One case group only is processed, the one the condition of which if first
matched.
Syntax:
do
case condition : statements
[ case condition : statements ]
[ else statements ]
[ always statements ]
/do [while expression]
- A condition if followed by a colon or a newline.
The "else" and "always" keywords also, for simplicity.
- The "else" group is equivalent to "default" in the C's switch case.
- The "always" group, if present, is performed in any cases.
- May end with /do, /do forever, /do while expression.
When the forever or the while option are used, the construct becomes a DFA
(Deterministic Finite-state Automata). A break must end it.
Please note that a "break" must not be used at end of a case group (as in C):
it will exit the whole construct, not the case group!
The do until control structure
It is similar to the do while one. No "/do" required.
The block of statements is performed until the condition becomes true.
Syntax:
do
... statements ...
until expression
The enum construct
Enum, as in C, allows to assign sequential integer values to identifiers, but
in Scriptol, it allows to assign values of several types.
The identifier and the value are separated by a colon.
You can use also an equal to assign an integer, for the sequence continue from
this number.
Syntax:
enum: ZERO, ONE, TWO, THREE /enum
This assigns 0 to zero, 1 to one, and so one.
This is equivalent to:
constant integer ZERO = 0
constant integer ONE = 1
etc...
enum: ZERO:"0", ONE:"1", TWO:"2" /enum
This is as:
constant text ZERO = "0"
constant text ONE = "1"
etc...
Example of the one-line syntax:
enum ZERO, ONE, TWO, THREE
enum let ZERO:"0", ONE:0.1, TWO:2
enum ZERO, ONE, FOUR = 4, FIVE
The last example associates the numbers 0,1,4,5 to the identifiers.
These statements have no Php equivalent. They are even not converted into
Php statements. This is just a construct of the language the compiler uses.
A value may be a literal number or text and nothing else.
Indexing
The syntax of an index in a text or an array: is [index].
Indice must be a simple expression without square brackets embedded inside.
A simple expression is a literal number, an identifier, a function call,
or an arithmetical expression, and must be resolved as an integer value.
Range
The syntax of a range inside a text or an array is: [start..end].
Start and end are simple expressions as above.
The last item is included in the range. To exclude it, use the -- operator.
a[0 -- 100] is equivalent to a[0 .. 99]
a[x -- y] is equivalent to a[x..y - 1]
Numbers
Methods may be associated either to a variable or literal number.
Methods of integer (or int):
toReal() upgrade to real.
toText() convert to text.
setDyn()
Methods of real:
toInt() round to integer.
toText()
setDyn()
Methods on number:
toInt(), toReal(), toText(), setDyn()
Text
A text is a basic objet with methods, that holds a string of any character.
When a text is the argument of a function, the function uses a copy of the
text, not an alias on the original one.
An indice may be negative in slicing or splicing, not in indexing.
Syntax:
text s create a text.
s = "str" initialize.
s = s[i] get a char.
s[i] = s2 replace a char, s2 should be a one-char text.
s = s[i..j] get a sub-string, from i until j included.
s[i..j] = s replace a sub string.
s[i..j] = "" remove a sub string.
Methods on text
----------------------------------------------------------------------------
Return Method Function
----------------------------------------------------------------------------
text capitalize() convert the first char to uppercase.
int compare(text) compare lexicographically two texts (ignore case).
return -1, 0, 1.
text dup(int) return a text duplicated n times. Ex: "*".dup(10).
void fill(text, int) fill s with text n times.
int find(text t2) returns the position of text s2 inside the text.
return "nil" if no found.
int identical(text) compare, doesn't ignore case. Return -1, 0, 1
int len() return the length.
int length() return the length.
text lower() convert to lowercase.
text lTrim() remove heading controls/blanks.
void replace(ft, rt) replace each occurence of ft by rt.
text rTrim() remove trailing controls/blanks.
array split(sep) split a text into items separated by sep.
function toFunction() cast to function.
int toInt() convert to integer.
real toReal() convert to real.
text toText() convert a literal string to text (for C++).
text trim() remove heading and trailing control codes/blanks.
text upper() convert to uppercase.
text wrap(int size) wordwrap the text.
----------------------------------------------------------------------------
Dynamic variables
Are declared with the type "dyn".
Dynamic variables have the methods of all other types of primitives.
They have also "post-casting" methods, whose effect being to give them a type
inside an expression:
doInt(), doReal(), doNumber(), doText(), doArray(), doDict(), doBoolean(),
doFile(), doFunction().
It is possible to change the type of a variable, but this is not a part of this
manual (see Level 2 manual).
Sequence and list
A sequence is either a static (text) or dynamic, associative list (array or
dict).
List and sequence have same operators, but # and || that are proper to lists.
Operations on lists are these:
[] : index, slice, or splice.
+ : merge two sequences. Or push a scalar to a dynamic list.
- : remove a sequence from another one, or an item from a dynamic list.
= : compare two sequences.
in : test if an object is in a sequence.
# : intersects two lists (gives common elements).
|| : union without doubloons of two lists.
Array
An array is a dymamic and indexed list of object or literals.
An empty array is symbolized by ().
An array initializer is a list of expressions separated by commas and
enclosed between parenthesis. A variable is a valid element. The initializer
starts with the keyword "array".
If the array initializer has several values, this keyword can be omitted.
Ex: x = a + (8,9) the compiler recognizes an array
Ex: x = a + array(8) the compiler needs for the keyword array
Ex: array a = (3) the compiler guesses it is an array!
Elements of are retrieved by their position inside the array.
Ex: a[1] = "a"
a[2] = "b"
scan a ? print a[]
>>> should print: a b
When an element is added outside bound, it is just pushed at last position
into the array.
array a = () clear the array
a[2] = "b" b is the first item, index 0
a[1] = "a" a is the second item, index 1
scan a ? print a[]
>>> should print: b a
Multiple assignment is not concerned:
a[2], a[1], a[0] = ("x", "y", "z")
inserts the values in the order: z, y, x.
Making an array
Syntax:
array a create an array.
array a = (x,y,...) create and initialize an array.
The elements of an array may be any expression *** but boolean ones ***.
If you put the true value inside an array Php (4.0.6) will return always true
when you use the "in" operator, with any searched for value.
Indexing an array
Items inside an array are accessed by an integer number.
Syntax:
a[n] read the item with at position n.
a[n] = x replace the item at n by x.
a[n] = nil erase the item with at n
a = () clear the whole array.
a[n].upper() call a method on the dynamic element n.
An array may be read with an iterator.
One points out the first element with begin(), or the last one with end(). The
currently pointed out value is accessed by an empty indice: [].
One points out the next element with inc() or dec().
Interval in array
An interval is subscripted by a couple of positions.
a[pos..end] the range between "pos" and "end" included.
a[..end] from the start to position "end".
a[pos..] from position "pos" to the end of array.
a[..] get the whole array (useless)
a[pos] = nil remove an item (keys are renumbered).
a[pos..end] = nil remove a range of items (here also).
a[pos..end]= b replace a range by an array/item
Dictionary
A dict is a dymamic list of pairs key and value.
Keys are always texts. Values may be any objects. Key and value may be
variables.
The format for a pair key and value is: key:value.
(The Php equivalent is key => value).
An empty dict is symbolized by ().
A dict initializer is a list of pairs separated by commas and enclosed in
parenthesis.
Array and dict share same methods, but some ones are more relevant with array
and other with dict.
Making a dict
Syntax:
dict d create a dict.
dict d = (x:v, y:w,...) create and initialize a dict.
Indexing a dict
Items in an dict are accessed by a textual key.
Syntax:
d["key"] get the first item with the key "key".
d[key] = dyn replace a value or add the couple key, value
if the key is not already inside the dict.
d[key] = nil remove an item.
d = () clear the whole dict.
Interval and dictionary
The right way to use a dictionary is by the means of keys or iterator. In some
cases, it mays be useful to access a range of items directly.
When adding an element or another dictionary to a dict, by the way of interval,
push, unshift, Php generate a new key for the item. The new key is a number.
- If you replace a range by another dict, some of the items may be lost.
- This also does happen when merging.
- The keys of the replacing dict are not kept in changed dict.
Examples of display:
Should print all keys and values in the dictionary.
// creating the dictionary
dict d = ("a":"alia", "b":"beatrix", "c":"claudia")
// internal display
d.display()
// display by for
for k,v in d : print $k,$v; /for
// display by iterator
number i = 0
d.begin()
while i < d.size()
print "$i)", d.key(), d[]
d.inc()
/while let i + 1
Example: get the last couple
the order is important as d.end() move the pointer to the last element
v,k = d.end(), d.key()
Methods of Array and Dict
------------------------------------------------------------------------------
Return Name Function
------------------------------------------------------------------------------
dyn begin() point out the first item.
dyn dec() decrement the pointer.
void display() print the array.
dyn end() point out the last item.
int find(dyn) search for an item, return the index or nil.
void flip() values become keys and conversely.
dyn inc() increment the pointer.
int index() return the index of the pointed out item.
void insert(int, dyn) insert a value at the integer (not key) position. Pack
text join(text sep) convert into text with sep between elements.
text key() return the key of the pointed out item.
void kSort() order the indices, associations being preserved.
boolean load(text name) load the file into the array (see "file" in Php).
dyn min() get the lowest value.
dyn max() get the highest value.
void pack() Make elements of the array consecutives.
dyn pop() get and remove the last item.
dyn pop(int) get and remove the item at the given position.
void push(val) add an item at end.
dyn rand() return an item at random location.
dyn shift() get and remove the first item.
int size() return the number of elements.
void sort() sort the values in ascending order. Pack.
void store(text name) store the array into a file.
number sum() calculates the sum of items.
void unique() remove doubloons from values.
For numbers first kept, for others last kept.
void unShift(dyn) insert an item at the first position. Pack.
dyn value() get the value pointed out.
k,v = d.key(), d.value() read the couple key:value
------------------------------------------------------------------------------
File
File is another virtual object, for processing local or distant files.
For a complete explanation of the file system, see "fopen" in the php manual.
Syntax:
file fname declare a file.
fname.open(path, mode) open the file with the path, and the mode.
- Path types:
http:// http distant file.
ftp:// ftp distant file.
other: local file.
- Mode types:
"r" read only.
"w" write only.
"a" append at end of file, write only.
"r+" read or write at start of file.
t = fname.readline() read a line terminated by a newline code.
t = fname.read(int) read a block from the file.
fname.write(text) write the text into the file.
fname.close() close the file.
boolean = fname.eof() return true if end of the file reached.
The error construct
After the "open" statement, the control structure error /error or error ?
should be executed when an access error occurs. However the Php interpreter
may stop the program before the construct is processed, depending of the
configuration.
Ex:
fname.open("text", "r")
error? exit()
Scopes
To avoid confusion, Scriptol doesn't allow a same name to be given to different
variables in embedded scopes (for example, the global scope and the one of a
function), but successive scopes can reuse the same names.
Scope of variables
The scope of a variable is the block of statements inside which it is declared:
global, class, function or delimited block.
Delimited block are body of if, while, do, case, etc...
The header of the for control structure is a part of the body's scope.
Parameters of a function are inside the scope of the function.
Inside a function, if a variable is referenced before any assignment, it is
assumed referencing a global variable if it exists, otherwise this is an error.
Inside a method of a class, if it is referenced before any assignment, it
references to a member if this member exists, otherwise this is an error.
Global variables are not visible inside classes, but the external ones.
Scope of external variables
External variables (those of Php, Apache, etc...) are always in the scope,
since there is no control for them (look at the "External variable" section).
Thus, you have to know their name to avoid using a name that will become
that of a Php variable, when the "$" will be added to. Or you should
avoid to use all uppercase names.
If you use external variables inside a function, you must declare them as
"global", as the compiler does not manage them.
Class and object
A class is a structure which contains variables (attributes) and has functions
(methods).
Once a class is defined, it becomes a new type added to the language and
unlimited number of instances (objects) may be declared with this new type.
We use attributes and methods of the object with a command in the form:
x = object.attribute
object.method()
Example of a class declaration:
class car
...body...
/class
Example of attribute and method:
int theSpeed = 50
void car.speed(int i)
int x = theSpeed * 2
return x
Example of instance and method reference:
car mycar
print mycar.speed()
Constructor
A constructor is a method the name of which being that of the class, and that
is called when creating an instance of the class.
The syntax of an instance creation is:
classname instancename(arguments)
If the constructor has no arguments, the parenthesis must be omitted. Empty
parenthesis are not allowed here.
The constructor always returns a void type.
Static methods and attributes
It is convenient to store all functions relative to a task into a class and
declare them "static". You can then refer to these methods directly along with
the class name without the need for declaring an instance.
Ex: node, ext = Dir.splitExt(path)
Static attributes are also allowed (Php 4 has not support for that, but Scriptol
bypasses this limitation). A static attribut is common to all instances of the
class and inherited ones. Static methods can use only static attributes, as other
ones exist only in instances of the class,
Static methods can't reference other methods.
The "static" keyword may be omitted for a method. An error message is thrown at
runtime if it is attempted to use as static, a method that is not static (if it
use no static attributes...)
It is recommended to put the static modifier, in this case an error message is
thrown at compile time when a not static attribute is used.
Inheritance
A class may inherit from attributes and method of another one, if it is
declared as a subclass of it.
The syntax is:
class name is othername
The class "name" inherits of attributes and methods of "othername".
This works also for static attributes and methods.
Included files
The syntax to include an external scriptol file is:
include "filename"
Parenthesis are optional. Simple or double quotes are required. If you want
to use directly a Php file, and the compiler not to compile it, see below...
Native PHP
If you want to insert Php code directly into your program, use these symbols:
<- start of included code.
-> end of included code.
The symbol are removed and the Php code remain inside the compiled one.
The compiler doesn't process it, it is as a comment for the compiler, but
unlike comment it remain into the generated file. In fact, it may be used to
send comment into the Php code!
If you want to insert an entire Php page, use this:
<-include("thepage.php");->
You don't have to change anything in the page.
Library
Scriptol Php has no library and doesn't need for one. As it compiles into Php
code, it may use the Php library. Any Php function can be used directly.
No control is performed on arguments and return type of the Php functions.
The most frequently used are already present, and are listed below.
Useful functions
These functions come from Php, and are included in the common Scriptol
language. The Php name is given in the list if it differs of the Scriptol one.
number abs(number)
Returns the absolute value of a number.
text chr(integer)
Returns the ASCII character for a value.
Ex: chr(32) return a blank space.
boolean chdir(text)
Change the current directory. Returns true or false.
boolean delete(text)
Deletes a file.
(See: unlink)
void die(text message)
Displays a message and exits the program.
void eval(text)
Executes some code exactly as Php one, stored in the argument.
To execute a whole file, use "exec" instead.
void exec(text command [, array results])
Executes a command.
An array may be provided to get the lines displayed by this command.
void exit()
Exits the program. Can send a message.
int intval(text t, int base)
Convert a text to an integer, according to the base (default 10).
scalar min(scalar, ...) or max.
Min returns the lowest object among arguments.
Max returns the greater one.
boolean mkdir(text)
Creates a sub-directory.
file open(text nom, text mode)
Ouvre un fichier, retourne un objet file ou nil.
integer ord(text)
Get the ASCII value of a character.
Ex: ord(" ") returns 32.
text pad(text t, len l [, text c] [, int o])
Pad a text with blank space or the given string of chars.
t: text to pad.
l: length to reach.
c: text to add, the default are blank spaces.
o: options STR_PAD_LEFT, STR_PAD_BOTH, default is at right.
(See: str_pad)
number pow(number base, number exponent)
Return the power of a number.
number rand()
Generate a random number.
array range(int first, int last)
Generates an array of integers from first to last.
boolean rename(text oldname, text newname)
Renames a file. Returns true or false.
boolean rmdir(text)
Delete a sub-directory.
real round(real x, integer decinum)
Rounds x, with the given number of decimals.
number sqrt(number)
Returns the square of a number.
text str(number)
Convert a number to a text.
(See: strval)
void swap(dyn, dyn)
Exchange the content of two variables.
The arguments must be simple or indexed variables, not expressions.
text system(text commant)
Pass a command to the operating system. Returns the last line displayed.
Appendix I: Using the Java API with Scriptol
Scriptol implements declaration of Java objects thanks to the "java" modifier,
and providing the Java extension is activated (see at the install card).
In the same way you include files the content of which you want to use, each
Java class you use must be imported, with the full path according to Java's
style.
Once a Java class is imported, you declare instances and call methods exactly
as you do for Scriptol classes.
The syntax is:
import java classpath-classname
If the word "java" begins the path, the compiler recognizes it and the
modifier may be omitted:
Ex:
import java java.awt.Dialog ...is a valid declaration
import java.awt.Dialog ...is valid too
import java MyClass ...is a valid declaration
import MyClass ...is not valid for a Java class
If you declare your own Java classes, they must stay in separated files, and
the files must have the name of the class with the java extension.
It has to be compiled by javac.
Ex: The class MyClass must be stored into a MyClass.java file.
Appendix II: Differences with other languages
Apart the obvious differences in the syntax, you should be aware or some more
subtle difference between Scriptol and the other language you may be previously
used with.
Other languages
- Scriptol does not allow performing both assignment and test in an expression.
The statement if(x = y) in c++ both lets y assigned to x and tests if x is 0.
In Scriptol, this tests if x equals y. The == operator is not used by Scriptol.
- The statement x = x + 2, is written x + 2 in Scriptol. This is the way human
think. (Ex: my car has moved one km, rather than: my car has moved from the
current place to the current place plus one km!)
Php
- Variables are local by default in Php. In Scriptol, if they are not declared
in the local scope, they are global. Proper conversion is done by the compiler.
- A range of elements is denoted by the location of the first one and the number
of elements in Php. In Scriptol, by locations of the first one and the last one
included.
- There is no "elseif" in Scriptol, but several pattern-matching structures are
provided instead.
C++ and Java
- Scriptol does not allow to reuse the name of a variable in an embedded scope.
A variable inside a function can't have the name of a global variable or an
attribute.
- Global variables are not accessible inside a class, unlike in C++.
Python
- Tuples are objects in Python. They are constructs of the language in Scriptol.
You can't assign a name to a tuple.
- A sequence initializer has the format (a, b, ...) in Scriptol. This initializes
a tuple in Python. A tuple in Scriptol has the format a,b,... without parens.
- The ":" terminator is required in Python at end of heading. It is required in
Scriptol only if the block of statements starts on the same line that the
heading.
- A range in Python, [first:last] does not include the last element. It is
included in Scriptol (but a different syntax allows not to include it).
I.N.P.I. registered #114223 - Oct 12, 2001 (c)copyright by D.G. Sureau
Main site: www.scriptol.com
Open-source repository: www.scriptol.net