Scriptol PHP
Common reference manual
(c) 2001 by D.G. Sureau
www.scriptol.com


Overview
About this manual
Compiling a Scriptol program
Scriptol file
Scriptol in html page
Statement
Comment
Symbols
Identifiers and keywords
Variable or primitives
 Declaration
Constant
External variables and constants
Assignment
 Multiple assignments
  The complete rule
  Reversing assignment
 Tips
Operators
 Precedence
Expression
Function
 Arguments of a function: the alias modifier
 The "main" function
 Using a variable as a function
Print and echo
 Print
 Echo
Control structures
The if construct
 One-instruction
 Multi-lines
The composite if constrol structure
The for constol structure
 One-instruction for
The scan construct
The while constol structure
 The while let option
 Simplified syntax
 The forever option
The do while construct
The do case construct
The do until constrol structure
The enum construct
Indexing
Interval
Numbers
Text
 Methods on text
Dynamic variables
Sequence and list
Array
 Making an array
 Indexing an array
 Interval in array
Dictionary
 Making a dict
 Indexing a dict
 Interval and dictionary
Methods of Array and Dict
File
 The error construct
Scopes
 Scope of variables
 External variables
Class and Object
 Constructor
 Static methods
 Inheritance
Included files
Native PHP
Library
Useful functions
Appendix I: Using the Java API with Scriptol
 Full example
Appendix II: Differences with other languages
 Other languages
 Php
 C++ and Java
 Python


Overview


 Scriptol PHP is the first version of the new Scriptol programming language.
 The next version will produce C++ code, and other will follow.
 The goal of the language is to be simple, natural and thus to reduce risk of
errors by the programmer. Scriptol means to "Scriptwriter oriented language".
 I use PHP as a back-end first, because I think the need is crucial for an
Internet language that, apart to be natural and easy to learn, allows for
complete error checking at compile time and not at run time.
 Scriptol may be embedded inside a html page and is converted to the same page
with PHP code, ready for the Net. It has the simplicity of ASP, but works on
all Unix station, thanks to PHP.
 The language has been defined according to the seven rules displayed on the
site.


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


 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.

 Options are:
 none     (no option) run a scriptol file, compile it if needed.
 -web:    compile code embedded inside html page and make a php file.
 -php4:   add the .php4 extension rather than the .php one.
 -run:    compile if needed, then always invoque the Php interpreter.
 -build:  recompile the file and all included ones. Don't run the program.

 The options can be abbreviated at the first letter, excepted the php 4 one
that is abbreviated with the 4 number. In short:
-b      forces to compile.
-r      forces to run.
-4      change to the ".php4" extension.


Scriptol file


 A Scriptol file holds a sequence of statements.
 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.
 The file may have the sol extension or any other, and will be converted into a
file with the php extension.


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      a dynamic list of objects
 dict       a list of couples 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.


External variables and constants


 The $ is used by Scriptol to denote variables of the Php language.
 Their scope is external, they are not tested for type. They are
usable inside the body of a class unlike global objects.
 They are transmitted directly to the target file, as functions.

 The syntax for a native Php constant is:
   $(constant_name)
the $ sign and parenthesis are removed into the Php code. The scope is external.


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 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 or dict.
- 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...)

Tips


 Multiple assignement at function call is converted in a Php List() statement.
This statement assigns elements from right to left. This may causes order is not
what expected when elements are in the form a[index], b[index], etc...
 The expected array's content is:  array( 0: value0, 1: value1, ...)
but it is rather that:  array(...  1: value1, 0:value0)
 Try a.kSort().


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 $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.
  void main(array arglist, int argnum)
    print argnum, "arguments"
    scan arglist
      print arglist[]
    /scan
  return
  main($argv, $argc)    ` argv and argc are external Php variables.


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.


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-name expression ? statement
 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 a = 5
    a + 3
    print a
  /if

  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 constrol 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 constol structure


 This constrol 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.

 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 x in a..b
        print x
      /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 ? basic-statement

 Ex:  for w in mylist ? print w
 Ex:  for x in 10..1 step -1 ? 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 ? 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
     print a[] * b[]
   /scan
 or:
   scan a,b? print a[] * b[]


The while constol structure


 One-instruction
   while expression ? 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
constrol structure (not the generated one).


Simplified syntax


 A while with the let option may be written simply as:
   while condition
   ...statements...
   let incrementor
 This is even the recommended syntax.
 Ex:
   while x < 10 ? print x; let x + 1


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 constrol 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 constrol 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...

  The one-line syntax is (? is optional):
  enum [?] ZERO, ONE, TWO, THREE
  enum [?] ZERO:"0", ONE:0.1, TWO:2

  Example:
  enum ZERO, ONE, FOUR = 4, FIVE
  This associates the numbers 0,1,4,5 to the identifiers.

  Example:
  enum READ:"r", WRITE:"w", APPEND:"a"
  file f = fopen("test", READ)

  These statements have no Php equivalent. They are even not converted into
Php statements. This is just a construct of the language for the compiler.
 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.


Interval


 The syntax of an interval 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. For exclude it, use the -- alternate
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.
text     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     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 associative lists are these:
 []   : index, slice, or splice.
 +    : merge two sequences.
 -    : remove from a sequence, another one.
 =    : 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 associative 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!

 The order of items inside an array is not their numerical indice, that are
only keywords to retrieve the items (according to Php).
 Ex:  a[1] = "a"
      a[2] = "b"
      scan a ? print a[]
      >>> should print:  a b
      array a = ()                clear the array
      a[2] = "b"                  b is the first item, index 2
      a[1] = "a"                  a is the second item, index 1
      scan a ? print a[]
      >>> should print:  b a
 The second assigned item has the second position, but its index is 1.
If you omit to clear the array, the initial positions of the indices will be
kept.


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


 The items inside an array are accessed by the position.
 Syntax:
  a[pos]                    read the item at position pos
  a[n] = x                  replace the item at position n.
  a[n] = nil                erase the item at position 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 (here also).


Dictionary


 A dict is a dymamic list of couple key and value.
 Keys are always texts. Values may be any objects. Key and value may be
variables.
 The format for a couple 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 couples separated by commas and enclosed by
parenthesis.
 Array and dict share the 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
case, 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.

  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
------------------------------------------------------------------------------
array   append(array)     concatenate two arrays.
void    arrange()         renumber integer keys from 0 to n.
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 an item at the integer position (not a key).
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 at the "file" function of Php.
dyn     min()             get the lowest value.
dyn     max()             get the highest value.
dict    merge(array/dict) merge two lists. Values of the second one replace
                          those of first one when keys are identical.
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.
number  sum()             calculates the sum of items.
array   unique()          remove doubloons from values.
void    unShift(dyn)      insert an item at the first position.
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 an 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 outside the body's scope.
 The parameters of a function are inside the scope of the function.
 Inside a function, if a variable is referenced before any assignment, it
references to 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 Php ones.

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.


Class and Object


 A class is a structure which contains variables (attributes) and has functions
(methods).
 Once a class is defined, it adds a complex type to the language and an
unlimited number of instances (objects) may be declared with this new type.
 Then, we use attributes and methods of the object with a command in the form:
   object.attribute
   object.method()
 A class may inherits from another class's items (members) with the "is"
operator.

 Example of a class declaration:
 class car is vehicle
   ...body...
 /class

 Example of a method declaration:
 int theSpeed = 50
 void car.speed(int i)
   int x = theSpeed * 2
 return x

 Example of reference:
 car mycar
 print mycar.speed()

Constructor


 A constructor is a method the name of which being that of the class, and that
is call when creating an instance of the class.
 The syntax of an instance creation is:
 classname instancename(arguments)
 If the constructor has not arguments, the parenthesis must be omitted. Empty
parenthesis are not allowed.
 The constructor must return a void type.

 Ex:
 class demo
  void demo(int x)           constructor
    ...
  return
 /class
 demo mydemo(10)             instance


Static methods


 It is convenient to store all functions relative to a task into a class. You
can then call these methods directly along with the class name without to
declare an instance.
 Ex: node, ext = Dir.splitExt(path)


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 methods.
 Ex:
 class car
   int power = 1500
   int getPower() return power
 /class
 class formulaone is car
   int speed
   int getSpeed()
     speed = getPower() / 4
   return speed
 /class
 formulaone f1
 print f1.power                 attribute of the superclass
 print f1.getPower()            method of the superclass
 print f1.getSpeed()            method of the class itself


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.

array union(array, array)
  Return the union of two lists, with no doubloons.

array unique(array)
  Remove doubloons among values.


Appendix I: Using the Java API with Scriptol


 Since the version 1.0m, Scriptol implements the 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 be 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.

Full example


 import java.awt.Dialog           the Dialog class imported in name space
 Dialog myDialog                  an instance is declared
 myDialog.setVisible(1)           a method is called



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 previous language you may be used
with.

Other languages


- Scriptol doesn't 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 is x equals y. The == operators 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. This is converted automatically.
- A range of elements is denoted by the number of the first one and the number
  of elements in Php. In Scriptol, by the first and the last element of the
  range.
- There is no "elseif" in Scriptol, but several pattern-matching constructs are
  provided instead.

C++ and Java


- Scriptol doesn't 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
  parenthesis.
- The ":" terminator is required in Python at end of a heading. It is required
  in Scriptol only if the body of the construct starts on the same line that the
  heading.
- A range in Python, [first:last] has the last element not included. It is
  included in Scriptol (but a different syntax allows not to include it).





I.N.P.I. registered #114223 - October 12, 2001 (c) copyright by D.G. Sureau - www.scriptol.com