Script programming language

Complete reference guide for Script 3.

This guide is used for the Script compiler in C++ (solc) or JavaScript (solj).
The Script PHP (solp) compiler uses Script 2.
For older versions of compilers, see Script 1.

The language is fully implemented in the Script compiler in JavaScript, but some extensions (promised, asynchronous/await) are absent in the C++ version.

Home: https://www.iqlevsha.ru/

Resume Summary

General provisions

The new Script programming language can be used with interpreters and compilers.
There is a version of Windows and Unix for each compiler.
The goal of language is to be simple, natural and therefore reduce the risk of mistakes. Scriptol means: "Scristwriter Oriented Language" or "scriptwriter's language" in French. It is a generic language designed to create dynamic web pages, scripts, and GUI applications. It can also be a scripting language for applications that process or create XML documents. The scriptol can be embedded in an HTML page and converted to the same page with PHP code ready for Net and fully portable. The language was determined according to seven rules described on the site.

About this guide

Note that the [] characters included in the statement syntax are not part of the language syntax and specify an option element, except for indexes and intervals that use these characters exactly.

Compiling Script into JavaScript

To run the command line, you must install Node.js. This option is set automatically after loading into Windows. On Linux, enter the following command:

sudo apt-get install nodejs

Or equivalent, depending on distribution.

To compile a program in JavaScript, the command:

solj [options] nomfichier 

If the source is already compiled, the JS program is interpreted, otherwise it is compiled before interpretation if there is no error.
As long as the source has errors, the new "solp nomficher" command will compile it. If the source is an HTML page, it does not start after compilation.

Compiler options:

 aucune: compile un script en PHP/JavaScript ou le lance si déja compilé.
 -w     compile du code inclus dans une page et crée un fichier HTML.
 -j     génère un fichier JavaScript à inclure dans une page HTML.
 -r     force l'exécution. Compile si besoin seulement.
 -c     recompile le fichier et fichiers inclus. Le programme n'est pas lancé.
 -v     affiche plus d'informations lors de la compilation.
 -q     pas de message de compilation.

These letters can be combined into one option. Thus, -be is equivalent to -b -e.

Also works in the latest versions of Powershell on Windows .

Change extension and runtime

The solj.ini file can specify the path to the scriptol.js file and the extension of the generated HTML file. Exempli gratia:

lib="c:/scriptolj/scriptol.js
htmlext=".php"

My first program

A Script source is simply a text file containing inside commands, one per line.
Examples:

   print x * 2
   print x + (y / 2)

Using a text editor such as Advanced Editor, enter the following line:

   print "Bonjour le monde"

Save to bonjour.sol file.

When working in a command line window (MS-DOS under Windows, console under Unix), just enter:

   solj bonjour         ...ou
   solp bonjour

You can also build an executable file using the command:

   solc -bre bonjour

and run the created program bonjour.exe.

It is possible to work with both the editor and the console window.

Project Script

The project file is not required.
In Java or PHP, a program is a source that includes other sources. Scriptol retains this structure.
The scripting source must have an include statement for each file whose content is used. The compiler calculates dependencies at several levels of inclusions and among mutual inclusions.

Source Script File

The Script file must have the extension "sol," and will be converted to a php extension file, or cpp and hpp, or an executable file.
This is a form of source, we will have a script or application.

Director's script
A script source is a sequence of statements and definitions of functions or classes. It can include other files containing declarations of functions, variables, classes.

Application
The application file contains only function, variable, and class declarations. The main source is the one that passes in the compiler command line, it must contain the "main" function, and the command to call this function (void below), return 0 main ()//run the program.

Language features

Scriptol can be defined as:

Case sensitivity:

Identifiers:

Numbers:

It depends on the target language .

Transform (cast):

Object-oriented:

XML-centric:

Reactive programming

HTML page

For Script code to be compiled into PHP on an HTML page, it must be included in the following tags:

<?sol
   ... code scriptol ...       
?>

The last line of Script must end with a semicolon or a line break before the character?>

Testing HTML pages If you installed a server such as Apache or Xitami or Windows Server on your computer and configured it to recognize the php extension, your code will be processed like on the Internet, after compilation in PHP. Otherwise, it will redirect you to a test file. HTML dynamic page, and then execute PHP code:

solp -w mapage
php mapage.php > test.HTML

To compile Script code into JavaScript in an HTML page, place it in the following markers:

<scriptol>
... code scriptol ...
</scriptol> 

Preparation

The statement ends with a semicolon or the end of a line. When an operator exceeds the width of a string, it is combined with the next string if it ends with a comma, an operator, or any other character that cannot complete the statement. You do not need a character in the next line to continue. Multiple statements on a single line are separated by semicolons. This can be useful if you put Script code on an HTML page and the editor joins the lines!

Comment

 Copyright: The # symbol is placed at the beginning of a line with a comment on the same line. This type of comment remains in the target code.

 The following source code comments are not saved in the target language:

//comment goes from character to end of line.

/ * and */contain a comment on several lines.

Symbols

Script language never uses the same character for conceptually different purposes.

+     addition
-     sousctraction
*     multiplication
/     division
=     opérateur d'assignement.
<     moins que.
>     supérieur à.
<=    inférieur ou égal.
>=    supérieur ou égal.
;     est un terminateur d'instruction.
,     sépare les éléments d'un initialiseur ou d'un tuple.
:     attache un corps à une en-tête, une valeur à une clé...
.     associe la référence d'une méthode à  un objet.
()    regroupe des sous-expressions, les paramètres d'une fonction.
..    sépare les limites d'un intervalle.
--    intervalle avec la limite supérieure non incluse.
[]    contiennent un index ou un intervalle.
?     sépare condition et action dans une structure d'une  seule ligne.
!=    opérateur de différence.
<>    autre opérateur de différence.
&     et binaire ou intersection de tableaux.
|     ou binaire ou union de tableaux.
<<    décalage à gauche.
>>    décalage à droite.
and   et logique (sur valeurs booléennes).
or    ou logique.
not   négation logique.
mod   modulo  (C utilise %).
^     xor.
#     commentaire de copyright.
//    commentaire de code source sur une ligne.
/* */ commentaire sur plusieurs lignes.
~~    début et fin d'un bloc de code cible à insérer. 
`     début et fin d'un template, chaîne sur plusieurs lignes.
@     suivi par un identifieur externe à insère dans le code.

Identifiers and Keywords

Identifiers are the names of variables, functions, and objects. They begin with a letter followed by letters, numbers, or underscores. They cannot be distinguished by case: you cannot give the same name to two different objects, one in capital letters, the other in lowercase. Keywords are reserved words of the language, they are lowercase.

Variables or primitive

Primitives are basic objects. When they are arguments to a function, the function uses a copy of its contents, values, and does not modify the original, while it uses an alias for other objects.

Scriptol's primitives are as follows:

var        élément générique de array ou valeur de dict.
number     toute sorte de nombre (jusqu'au double du C++).
int        un nombre arrondi à la partie entière sur 32 bits. 
integer    identique.
natural    entier non signed de 64 bits sauf 0. 
real       un nombre avec des décimales.
bool       la valeur vrai ou faux.
text       une chaîne de caractères. 
array      une liste dynamique indexée d'objets.
dict       une liste associative formée de couples clé:valeur.
react      une variable reactive.
file       un fichier.

Import C uses other special types:

byte       type externe de C.
cstring    utilisé dans les déclarations externes en langage C (traduit par char *).

Literal

Letter numbers write:

123          entier (int)
123n         naturel (natural)
123.0        réel (real)
0.123        réel (real)
1.2e10       réel (real)
0xf8         hexadécimal
0b011        binaire   
true/false   booléen (bool)

Quotation marks and extractions

A literary text is written: "untext" or "untext."

Example:

  print "abc$xyz"
  print 'abc$xyz'

in both cases, abc $ xyz is displayed.

Issue codes

For characters that cannot be placed directly in the text, a special code is used :\For example, to display the sleeve, write: "abc\" def"

   \"      insère un guillemet double.
   \'      insère un guillemet simple.
   \n      insère a retour à la ligne.
   \t      insère une tabulation.
   \\      insère l'anti-slash lui-même.

Suppose you want to assign the variable a with this particular text: my "cute" machine. You can't put it in quotation marks: a = "my "beautiful" machine" The compiler won't know how to handle it! A special code is used to say that the quotes are in the text, rather than limiting it, it is\a = "ma\" jolie\" car" You can also alternate types of quotes: a =" ma'jolie" car "or a =" ma "jolie" car "

Cartoon line

Text can also be distributed over multiple lines in characters', for example, in ECMAScript 6.

Example:

x = `
     ligne 1
     ligne 2
    `

The return to the line can be a direct or entered release code.

x = "un\ndeux"            ...valide
x = "un
deux"                          ... non valide

x = `un
deux`                       ... valide

Variable in line

If the string is enclosed in double quotes, character sequences starting with $ are variable names.

   text xyz = "def"
   text t = "abc$xyz"

The string "abc" is assigned, followed by the contents of the variable abc. This is the so-called string interpolation .

{} characters can have special meaning in the target language and must be crossed out in a double line with the\symbol.

Plain quote texts preceded by $ are not interpreted at all.

  text t = 'av$er\n'

show: av $ er\n

Declaration

The variable declaration has the form:

type nom [ = valeur ]

Examples:

int x
text t = "demo"

As long as they are all of the same type, you can declare and initialize several variables at once.
Syntax:

type nom [= value], name [= value], etc...
int x = 1, y, z = 2

You can't mix multiple guys into one statement. Multiple assignments, as described below, cannot be made in one application.
The following shape is not valid:

int x, y = 0, 0      // non valide

While the following is recognized:

text a = "a"
text b = "b"
text c, d
c, d = [a, b]

Constant

The const modifier indicates a primitive whose value cannot be changed. You must assign a value when declaring.

Syntax and examples of declaring constants:

const type nom = valeur
const int X = 1
const bool B = true
const text T = "texte quelconque"

Constants are usually in capital letters .

There are preset constants that are keywords of the language:

true        correspond à une expression vraie.
false       le contraire.
zero        la valeur 0.
nil         objet non trouvé dans une séquence (Not In List)ou symbole de suppression.
null        assigné à un objet quand il n'est pas encore initialisé.

PI is a given constant for representing a mathematical symbol.

Neil and Zero

Nil means "not in the list," while null means "doesn't matter" or "declared but undefined."

Neil is not a real value, but rather a construction of language. When read, it indicates that the object was not found in the list search. An entry removes an item or interval from the list. Variable cannot be initialized with nil.

Common examples:

array a = [1,2,3,4,5]
a[1..3] = nil

Now the content of the table is [1.5].

int i = "démo".find("x")
if i = nil print "Non trouvé"

Since "x" is not in the text "demo," the message "Not found" will appear.

Here are the meanings of the nile in different contexts...

When creating a code, C++ nil is replaced by the following values:

 bool         false
 int          -1
 natural      -1
 real         -1
 text         ""
 array        []
 dict         {}
 file         null
 objet        null
 var          selon le type du contenu.

When creating PHP code, nil is replaced with false for the number, with "" for the text.

When JavaScript code is generated, nil is -1 for the number, "" for the text .

Zero

The null keyword is converted to "null" in PHP, "NULL" in C++, and "undefined" in JavaScript;

If an identifier is null, it cannot be used or used until it is. It can only be compared in one condition with the null keyword.

Example of use:

text a = null

Variable "a" can be assigned, but is bound only for comparison with zero value, otherwise an error message will appear.

Appointment

Simple assignment syntax:

identifieur = expression

The assigned value must be of type variable:

int i = 10
int j = "343"            ... incorrect

However, primitive builders allow transformations.

Increased assignment

When an operation is performed on a variable and the result assigned to the same variable, you can simplify the statement by increasing the assignment (from one operation).

Increased assignment syntax:

identifieur opérateur expression

For example, add 10 to x and put the result in x. Instead of writing x = x + 10, we write easier: x + 10

Possible operators are + - */mod <<>> & | ^ #
Examples:

a = 1              ... donne à a la valeur 1.
a + 1              ... ajoute 1 à a.
x * y              ... remplace le contenu de x par le résultat x * y.
a * (x + 2)        ... multiplie a par l'expression.
a = a * (x + 2)    ... comme ci-dessus.
a & b              ... remplace le tableau a par l'intersection des tableaux a et b.

Note that in the condition test, x + 10 simply returns the result of adding 10 to the content of x without changing x. In the enlarged instruction, this result is assigned to x.

if x + 1 : ...     ici x n'est pas modifié.

Destructive appointments

A tuple of values can be assigned to a group of variables. Syntax and example:

   nom [, nom]* = expression [, expression]*

   x, y, z = 1, x2, 8

The number of expressions on the right must match the number of expressions on the left.
Unless there is only one expression on the right, it will be assigned to each variable in the group.
Note that the function can return multiple values and will be assigned to a group of variables.
Examples:

   x, y, z = 0
   a, b = mafonction()

Instead of a multiple declaration, multiple assignments can be made to different types of variables.
Example:

  int x
  text t
  x, t = 1000, "abc"

Multiple assignment can be used with array elements. Arrays have a dynamic size, so the target number should not correspond to the number of elements, and if the array has only one element, only the first variable will be assigned.
Example:

  x, y, z = [1, 2, 3, 4]

Equivalent: x = 1, y = 2, z = 3.

  x, y, z = [1]

Equivalent to: x = 1.

You can assign multiple variables at the same time using:

In the case of an array or dictate, a tuple, a function that returns multiple values, variables 1-n are assigned to elements 1-n in the same order. If the number does not match, it is an error.
If the function returns only one value, the same value is assigned to all variables on the left.

Exchange the contents of two variables:

var a = "alpha"
var b = "beta"

a,b = [b, a]
print a, b

What will show: beta, alpha.

Operators

Comparison operators:

=   égal
<   inférieur à
>   supérieur à
<=  inférieur ou égal
>=  supérieur ou égal
!=  différent
<>  différent

The " in" operator checks for the presence of an element in the sequence: text in the text, an object in the array, a value in between.

   if "a" in line  print "dans le texte"
   if x in 1..10  print "dans l'intervalle"

Binary operators:

  &  (et)
  |  (ou)
  ^  (ou exclusif)
  ~  (non)
  << (décalage à gauche)
  >> (décalage à droite).

Array operators are:

   &  (intersection)
   |  (union)
   ^  (complément d'intersection).

Precedent

Unary operators have precedent over binary operators. Between operators of the same arity, the preceding values are given by parentheses.

Expression

An expression is a combination of values and operators.

Arithmetic expressions

These are arithmetic values ​ ​ or function calls combined with these operators:

  +
  -
  *
  /
  ^        puissance
  mod     modulo, retourne le reste d'une division...

Example:

   print 100 mod 3     ... affiche 1 le rester de  100 divisé par 3.

Relational expressions

Arithmetic expressions can be compared using previously seen comparison operators.

The comparison returns a Boolean value of true or false (true or false). This boolean value can be assigned to a boolean variable or used as a condition of the control structure, for example, "if."

Logical expressions

A Boolean expression is a combination of Boolean values or expressions (relational or Boolean) and Boolean operators.
The logical operators are:

  and     et
  or       ou
  not     non

The expression "and" returns true if both terms are true, if not.
The expression "or" returns true if one of the two terms is true, false if both are false.
Example:

   bool x = true
   bool y = false
   if x and y print "vrai"; else print "faux"           ... doit afficher faux
   not(x or y)          ... est faux
   x and not y          ... est vrai

Binary expressions

Binary operators are those used by most languages:

 &  et binaire
 |  ou binaire
 ^  ou exclusif
 ~  négation binaire
 << rotation à gauche qui équivaud à multiplier par 2
 >> rotation à droite qui équivaud à diviser par 2

Text expressions

Text operators:

 =, <, >, <=, >=   comparaison de deux textes.
 +                 concaténation de deux textes.
 []                indexation, slicing ou splicing (voir chapitre Text).
 in                teste si un text fait partie d'un autre.

Example:

 text t = "préfixe"
 print t + "suffixe"
 ...affichera: préfixesuffixe

Dynamic list expressions

List operators (array, dict):

= < > <= >= <>  compare les valeurs de deux listes.
+               concatène deux listes (des doubles peuvent en résulter).
-               enlève d'une liste les éléments d'une autre (sauf doubles).
[]              indexation, slicing or splicing (voir Array et Dict).
in              teste si un élément est dans la liste.
&               intersection.
|               union.
^               complément d'intersection.

The intersection of the two lists returns items common to both. Merging two lists returns all their elements. Items belonging to both are saved only once. If one of the lists already has a duplicate, only the first instance is saved.

Precedent

Some programming languages set precedent rules, so when parentheses are omitted, it is known which term concerns each operator. Although the precedent was built in the Script parser, message errors will be sent if parentheses are omitted, as they are necessary for readability.
The only case where history is allowed without parentheses is for the unary operators: not, ~ The unary operator always applies to the following term, so to apply it to an expression, you need to place it in parentheses. Example:

  if not a and b
  if not (a and b)

The operator is not associated with the object "a" in the first, in the second - with the negation of the expression.

In compound assignments (see below), the first statement refers to the variable to be assigned with the expression to the right of it.

Function

The function is defined using an interface indicating how to call it, a set of instructors, and ends with the keyword "return."
Expected return type and argument type. Use "void" if the function returns nothing.

Syntax:

  type [,type]* nom ( argument [, argument]* ) [:]
    ... instructions ...
  return [expression [, expression]*]

Example:

  int multiply(int x, int y)
     int z
     z = x * y
  return z
 

This can be written more simply:

  int multiply(int x, int y)
  return x * y

The body of the function is a list of statements that include "return" statements as needed.
The end of the definition is a return with zero, one, or more values.

return
return x
return x, y, 5

If a function returns multiple values, it must have multiple return types and a return statement to multiple parameters (in the same order as return types).

Example:

  text, int, int coordonnees(int num)
    int x = matable[num].x
    int y = matable[num].y
  return "coordonnées=", x, y

Function call

A function call can assign zero, one, or more variables.

   mafonc()
   a = mafonc()
   a,b,c = mafonc()

Alias: navigating by value or by reference

When a function has objects as parameters, the parameter names are aliases of the objects, and any change in the function actually occurs on the original objects. By default, primitives are copies and alias objects. You can change it using the modifier: "pseudonym": the name of the primitive becomes the pseudonym of the original.

  void mafonc(number x)
    x + 1
    print x
  return

  void foncalias(alias number x)
    x + 1
    print x
  return

  number y = 5
  mafonc(y)
  print y
  ... doit afficher 6 puis 5

  foncalias(y)
  print y
  ...  doit afficher 6 puis 6.

Default values

If you specify a default value, the argument can be changed when the function is called. Full interface syntax:

 type [,type]* nom(type nom [= expression] [, type nom [= expression]]* )

Example:

  int increment(int x, int y = 1)
    x + y
  return x
  print increment(10, 5)          ...affichera:  15
  print increment(10)             ...affichera: 11

A default value of 1 was used to replace the missing parameter.

If a function interface has several parameters with a default value, you cannot skip one of them when calling all of the following without exception. Parameters cannot be recognized by type.
If you want to write a function with a variable number and parameter types, then you need to use an array or dictionary instead.

Example:

  void param(dict parlist)
    taille = parlist["taille"]
    nom = parlist["nom"]
    valeur = parlist["valeur"]
  return

In this example, the variables "size," "name," "value" are global, and it is assigned to the dictation content in the arguments.

Scope and function

A scope is the level of visibility of declared objects. The function opens a new scope for all variables declared inside. If the function is in the global scope, the function displays all global variables compiled before the function.
Cannot re-write a variable with the same name as a global variable to a function.
If the function is a class method, the function displays all variables declared in the class before the function.
Objects declared in the function are visible in control structures within the function.

Hand function

It is useful to be able to pass arguments to the program from the command line.
Script (such as PHP) uses the PHP variable $ argv." To simulate how C++ moves from arguments to the program, create the "main" function and call it with $ argv in the argument (and $ argc if necessary):

  int main(int argnum, array arglist)
    print argnum, "arguments"
    for arg in arglist
       print arg
    /for
  return 0

  main($argv, $argc) // $argv and $argc sont des variables système. Elles sont assignés automatiquement.

The int return type is required if the source is compiled into a binary file.

When a program is compiled in C++, a manual call is useless.

Print and echo

Echo

Displays an expression or a comma-separated list of expressions with no spaces between them and no return to the end string (as in printing).

Syntax: Echo Expression [, expression]

Example:

  x = 5
  y = 20
  z = 1
  echo "values", x, y / 2
  echo z

On the screen it will look like this:
value 5101

Example:

  echo "demo", 5
  echo "next"

displaying: demo5next

Print

A more complex display is obtained using the print statement. The expressions are separated and we go to the line at the end of the statement.

Syntax: Printed Expression [, expression]

Example:

  print "demo", 5

displaying: demo 5

A simple print statement without an expression sends a return to the string.
Example:

  print

Contribution

Use the input command to enter text from the keyboard.
Text can be displayed before text is entered.

Example:

  text name
  input name
  print name

Example:

  input "who are you? ", name

The input command must be preceded by a variable, which must be any type of text or number.

Control structures

Control structures:

if
   if else /if.
   if une instruction.
   if composite.
for
   for /for.
   for une instruction.

while
   while let.
   while une instruction.
   while forever
do while
   do until.
   do /do while.
   do case.
switch case
enum
   enum simple.
   enum dictionnaire.

JavaScript only:

to for /to
to while /to
to une instruction 

break and continuity can be used in loops.

The control structure of one instruction has the form :

   mot-clé-de-structure expression let instruction
ou mot-clé-de-structure expression ? instruction
ou mot-clé-de-structure expression instruction commençant par un mot-clé.

There is no end marker other than the end of the line. The statement is a base statement and cannot be a different construct.
The "let" statement is always the last part of the controlling structure and can be the only one. Symbol "?" is simply an abbreviation for "let." Let is required if the statement is an assignment or function call, but optionally if it is followed by a keyword. If "else" or "let" ends the control structure on the same line, the statement must end with a semicolon.

The multiline control structure has the form:

nom-structure expression [:]
    ... instructions ...
/nom-structure

A point-to-point character is optional (unless the statement is on the same line).

Yew

Conditional control structure from row to shape:

if condition ? instruction : instruction

It says: true state? action: otherwise action

Examples:

if a = 5 ? break
if a = 1 ? print "un" : print "plusieurs"

Cartoon line

Syntax:

  if condition-booléenne [:]
    ... instruction ...
  else                                      ...optionnel
    ... instructions ...
  /if

N.B.: A point-to-point character is optional after a condition, like a semicolon after a statement, but it is required when joining strings.

Example:

if (x + y) > 8
    print "> 8"
    print x
else
    print "<= 8"
/if

if (x + y) > 8 : print "> 8" ; print x ; else print "<= 8"; /if

If composite

Syntax:

if expression non-booléenne [:]
   operateur expression : instructions
   operateur expression : instructions
        ...
else
   ... instructions ...
/if

A non-Boolean expression is a variable, literal, or any expression that does not return a Boolean value of true or false.
The keyword "break" does not fit at the end of the group, as in C. Breaking will cause the control structure containing the if construct to exit.
Valid operators are =, <,>, <=,> =,! =, <>, in, else.
"else" here is equivalent to "default" of the switch.

Example:

if a
  = 1: print 1
  = 2: print 2
  > 2: print ">2"
else print "<1"
/if

if x
  in [1,2,3]: print "premier"
  in [4,5,6]: print "second"
  in [7,8]  : print "troisième"
  else print "autre"
/if

For

Citter Control Structure conducts either an integer interval or an array and assigns each element to a variable in turn.

Syntax for interval:

for variable in début..fin [step s] [:]
   ... instructions ...
/for

The start, end, and step are identifiers or literals.
The step is optional and the default value is 1.
A thin boundary is included in the interval if the interval symbol is.. "" and not if the symbol is "-."
The end may be less than the beginning if a "step" is present and contains a negative step.
A container variable can be declared in the header. In this case, it is local to the controlling structure.

Syntax for list:

for variable in expression-tableau [:]
     ... instructions ...
/for

In this case, the content of the expression is viewed and each element is assigned to a variable. This expression must be a table or combination that creates a table.

Examples:

for i in 1..10
      print i
/for


for w in montableau
    print w
/for


for w in arr1 + (arr2 & arr3[0..5])
    print w
 /for

For instruction

Short statement syntax:

  for variable in liste let instruction-basique

Examples:

  for w in maliste let print w
  for x in 10..1 step -1 let print w + 10

Get Index and Value

Loop to scan the associative table by value. That amounts to... from JavaScript, while for.. in in JavaScript scans keys.

for var v in d let print v        // affiche les valeurs 

But you can get the key and value:

for text k, var v in d let print k, ":", v // affiche clés et valeurs 

It also works on a simple table:

array a = (10,20,30)
for int indice, int val in a
  print indice, ")", val
/for

It will show:

1) 10
2) 20
3) 30

Wile

The while control structure is a conditional loop.

The syntax of one command is:

   while expression let instruction

Standard syntax:

  while expression [:]
     ... instructions ...
  /while

Example:

  int x = 10
  while x <  20
     print x
     x + 1
  /while

The "break" instruction comes out of the loop.
A "continuous" statement ignores all of the following and starts a new loop.

While let

This syntax is recommended to avoid the risk of endless loops.
The statement that changes the value of the tested expression as an iteration condition is moved after the/while marker with the "let" command.

  while condition
    ...instructions...
  let incrementation

Example:

  while x < 10
     if (x mod 2) = 0 continue
     print x
  let x + 1

A continuous statement skips the let statement.
There is no equivalent in C or PHP, as the continuous statement skips the following code, including the x increment, which leads to an infinite loop.

Examples of instructions:

   while x < 10 let x + 1
   while x < 10 : print x; let x + 1

Do until

The block of instructions between do/do markers is the new visibility space, and the included instructions are subtracted depending on the possible condition.

General syntax:

do
   ... instructions ...
until [ condition ]

The instruction block is executed as long as the condition is false and is left when the condition becomes true.

The syntax for do until is:

do
   print x
   x + 1
until x = 10

Do case

This is a powerful pattern-matching design. It contains one or more groups followed by an optional "default" and an optional "alveis." Only one group of check boxes is executed, the first of which meets the requirements. Always runs by default when conditions are not met.

Field syntax:

do
    case condition : instructions
    [ case condition : instructions ]
    [ default instructions ]
    [ always instructions ]
/do [while expression]

Examples:

do
case nom = "pussycat":    print "c'est un chat"
case nom = "flipper":        print "c'est un dauphin"
case nom = "mobby dick": print "c'est une baleine"
default
   print "un autre animal"
/do

int state = ON
do
case state = ON:  counter + 1
case state = OFF: break
always
    state = getState()     ` une fonction quelconque
/do while forever

Automation that reads its state from one and continues to rotate until the OFF state created by the called function is detected.

To while

The end marker do can be supplemented with a condition, while or forever.
The instruction block will be executed at least once and as long as the condition is correct.

Syntax:

do
   ... instructions ...
/do while expression


do
   print x
   x + 1
/do while x < 3

Parameters:

Switch flag

Syntax:

swith nom-variable
case int/real/text : bloc d'instruction
... séris de  cases ...
default: bloc d'instruction
/switch

You can compare the variable:

Example:

real x = 0.8


switch x
  case 0 : print "0"
  case 0 .. 1 : print "dans l'intervalle"
  case 1,0.5, 0.8, 1 :  print "dans l'intervalle"
  defaut:  print "pas trouvé"
/switch

It is not a mistake to compare a variable of one type with a value of another type, unlike an assignment. For example, the whole and the real. The target language will determine the result of the comparison.

Break and continue

The command to exit the loop.
An example of using the keyword "forever," which intentionally creates an infinite loop.

int x = 0
while forever
   print x
   if x > 100
      break
   /if
   x + 1
/while

When x reaches 100, the break statement causes the program to jump beyond/while, to instantiate after the while structure.

Continuous

This second command allows you to skip all instructions from the current position to the end of the structure, so start a new cycle.

int x = -1
while x < 20
   x + 1
   if (x mod 2) = 0 continue
   print x
/while

In this example, only even values of x are displayed, because when an odd value is detected, the condition x mod 2 is checked and a continuous command is executed.
In this example, I inserted an increment x in the first line. If this were placed after the command continued, it would result in an infinite loopback as the increment would have been passed. Syntax while.. Lethe avoids it.

Transfer

Enum allows you to sequentially assign values ​ ​ to identifiers, and in Script it allows you to assign non-integer values ​ ​ - real or text.
By default, an integer is assigned from zero and incremented for each identifier in the list.
A double point is used to assign a specific value to an identifier, and an equal sign is used to restart that value.

Syntax:

enum
  identifieur [ : value | = value ]
  [ identifieur ...]*
/enum


enum:
    Z, UN, DEUX, TROIS
/enum

This assigns 0 Z, 1 UNE, and so on. This is equivalent to:

const int Z = 0
const int UN = 1
etc...


ou:


enum: Z:0, UN:1, DEUX:2 /enum

A more complex example of assigning heterogeneous values ​ ​ and starting a sequence:

enum
    Z : "a0",                     ...  assigne a0
    UN  : "a1",                  ...  assigne a1
    TROIS,                        ...  assigne 0
    QUATRE : 3.15,            ...   assigne 3.15
    CINQ = 5,                     ...   assigne 5 et redémarre la séquence
    SIX                            ...   assigne 6
/enum

An example of a simplified syntax in a statement:

enum ZERO, UN, DEUX, TROIS

Indexation

Text or table hint syntax is [hint]. Index must be a simple expression with no nested brackets. A simple expression is a literal number, identifier, function call, or arithmetic expression and must be evaluated as an integer.

Interval

Interval syntax:

début..fin

To specify the list, enclosed in square brackets:

nom-liste[début..fin]

The beginning and end are whole expressions. The last element is included in the interval if the operator is not used: "-"

a[0 -- 100]        équivaud à [0..99]
a[x -- y]            équivaud à a[x..y-1]

Interval analysis:

0..10
x..y
x * 2 / 4 .. y + 10

You can use the interval to:
- check if the value is in the range: if x in 10.. 100
- scan interval: for x to 1.. 100
- extract part of the list: array b = a [x.. y]
- change part of the list to [x.. y] = other list

Gaps in the list

When indexing a list, the lower or upper limit of the interval may be omitted.

Il y a trois moyens pour découper une liste:
   array a = [x0, x1, x2, x3, x4, x5, x6, x7, x8]
   array b = a[..2]
   array c = a[3..5]
   array d = a[6..]

On obtient trois tableaux avec ces contenus:
   b:   (x0, x1, x2)
   c:   (x3, x4, x5)
   d:   (x6, x7, x8)

On les affiche:
   b.display()
   c.display()
   d.display()

On doit voir:
   array (
    [0] => x0
    [1] => x1
    [2] => x2
   )
et ainsi de suite...

To replace the interval with another list, just assign:
a [3.. 5] = [«a», «b», «c»]
The content becomes:
(x0, x1, x2, «a», «b», «c», x6, x7, x8)

With the same syntax, the sublisting is replaced by a list or element:
a [3.. 5] = «xyz»
Original tea list become:
(x0, x1, x2, «xyz», x6, x7, x8)

To delete a sublist, declare nil, "not in the list" (not in the list):
a [3.. 5] = nil
Removed sublist 3.. 5, which is (x3, x4, x5), we get:
(x0, x1, x2, x6, x7, x8)

You can check whether the value belongs to a sublist.
Example:

array a = ["un, "deux", "trois"]
if "deux" in a[2..5] print "dedans"

Text

The text is the main object with methods and contains a string.
If the text is a function setting, the function uses a copy rather than an alias in the source text.
Index can be negative in range, not indexing.

Syntax:

text s                 crée un texte.
s = "str"              initialise.
s = s[i]               prend un caractère.
s[i] = s2              remplace un caractère, s2 a un seul caractère.
s = s[i..j]            prend une sous-chaîne, de i jusqu'à j inclus.
s[i..j] = s            remplace une sous-chaîne.
s[i..j] = ""           supprime une sous-chaîne.

Literate text is a string of characters stained with single or double quotes.
The + symbol can be used with texts, and it is a concatenation of two lines.
Example:

text b = "préfixe"
text a = b + "suffixe"

Content a will be: "prefix."

Text methods

Retour   Méthode         Fonction

text     capitalize()    met la première lettre en majuscule.
int      compare(text)   compare lexicographiquement deux textes (ignore maj).
                         retourne -1, 0, 1.
text     dup(int)        retourne un texte dupliqué n fois. Ex: "*".dup(10).
void     fill(text, int) remplit avec le texte en paramètre dupliqué n fois.
int      find(text s2)   retourne la position du texte s2 dans le texte,
                         retourne "nil" si non trouvé.
                         (tester si = nil car <> nil ne va pas en PHP)
int      identical(text) compare, différencie maj/min. Retourne -1, 0, 1
void     insert(int, text) insère in text à la position donnée.
bool     isNumber()      retourne true si le texte contient un nombre.
int      length()        retourne la longueur.
text     lower()         met en minuscules.
text     ltrim()         supprime blancs et codes de contrôle au début.
text     replace(ft, rt) remplace chaque occurence de ft par rt.
void     reserve(int)    alloue la taille donnée pour utiliser comme buffer.
array    split(sep)      découpe le texte en éléments séparés par sep.
void     toFile(text)    sauve le texte dans un fichier dont le nom est en paramètre.
int      toInt()         convertit en entier
natural  toNatural()     convertit en naturel.
real     toReal()        convertit en réel.
text     toText()        cast une chaîne littérale en text (pour C++).
text     trim()          supprime blancs et codes de contrôle en début et fin.
text     rtrim()         supprime blancs et codes de contrôle en fin.
text     upper()         met en majuscules.
text     wrap(int size)  mots non coupés.

Dynamic variable

Declared with type: var.
Dynamic variables have methods of all other types of variables, but not methods of declared classes (see exter). When a variable is assigned to a var, a cast is required to assign the content to a typical variable.

Var methods:

Sequence and list

A sequence is a static (text) or dynamic (array or dict) list.
Lists and sequences have the same operators except & and |. Operations in lists:

  []   : indice, lecture ou modification de sous-liste.
  +    : fusion de deux séquences. Ou ajoute un élément à une liste.
  -    : supprime une séquence d'une autre, ou un élément d'une liste.
  =    : comparaison de deux séquences.
  in   : teste si un objet est dans une séquence.
  &    : intersection de deux listes (donne les éléments communs).
  |    : union sans doublons de deux listes.

Picture

There are two types of dynamic lists in Script:

 array:  (tableau) indicé par des nombres entiers.
 dict:    (dictionnaire) les clés sont des textes.

An array is an indexed, dynamic list of objects or literals.

An empty table is represented by [].
A literal table is a comma-separated list of expressions inserted between [].
A variable can be an array element.
The constructor begins with the keyword "array."

To show the contents of table a, we enter a.display () and get something from the shape:

  array(
  0 : un
  1 : deux
  2 : trois
  )

Create Table

The array constructor is of the form: array ()
The literary picture reads: [... values...] You can define an array by assigning a constructor, a literal, or a unique value.

Syntax:

  array a                               crée un tableau.
  array a = []                          crée un tableau vide.
  array a = [x, y, ...]                 crée et initialise un tableau.
  array a = [3]                         crée un tableau d'un élement.

Array elements can be any expression except the logical expression * * *. If you put the true value in a PHP array, each time you use the "in" operator, the true value will be returned with any value you search for.

A table can be declared without assigning content and subsequently populated:

  array a
  a.push("un")
  a.push("deux")
  a.push("trois")

Elements are found by their position in the table.
Examples:

  a[1] = "a"
  a[2] = "b"
  for x in a : print x
  ... doit afficher:  a b

Index Table

Array elements are available as an integer.
Syntax:

  a[n]                   lit l'élément ayant le numéro n.
  a[n] = x               remplace l'élément à la position n.
  a[n] = nil             efface un élément.
  a = []                 efface le tableau entier.
  a[n].upper()          appel d'une méthode sur l'élément n du tableau.

An empty index indicates the current item:

   a[]                        élément à la position courante.

An index can be any expression that evaluates to an integer. Expression cannot contain an array element.

  a[10 + x / 2]            valide.
  a[10 + b[5]]             n'est pas valide.

Because an array can contain any type of object, or even other arrays, a dynamic variable is required to read an item, unless it is associated with a type of item being read.

  array a = [ x, "two", 3 ]
  var x = a[1]                utilisation de var pour lire l'élément de type inconnu.
  text t = a[2]
  int i = a[3]

When you add an item outside the limit, it is placed last in the table.
When you assign an item with the following statement, the content changes depending on the target language:

  a[1000] = "x"

En PHP et JavaScript:
 array(
  0 : un
  1 : deux
  2 : le dernier
  1000: x
 )

En C++:
 array(
  0 : un
  1 : deux
  2 : le dernier
  3: x
 )

In PHP, index 1000 is only temporary and will change as soon as the statement changes the table.
The statement in the form a [n] = x is used to change the value of this index, you should not assign a table in a way that is suitable only for dictionaries (dict), as shown below.

Iterator

Table contents can be viewed by the iterator.
The first element is indicated by the begin () method, or the last with end (), the current element is obtained by an empty figure index [].

  begin()     pointe sur le premier élement et retourne sa valeur.
  end()       pointe sur le dernier élement et retourne sa valeur.
  inc()       déplace sur l'élément suivant.
               Retourne la valeur pointée avant, ou nil au-delà du dernier élément.
  dec()       déplace sur l'élément précédant. Retourne la valeur ou nil.
  index()     retourne l'index de l'élément pointé.
  value()     retourne la valeur de l'élément pointé.
  []          indice de l'élément courant.
  nil         signifie "not in liste" et est retourné par différentes fonctions
              quand aucune valeur ne peut être retournée.

Example of using table a:

  a.begin()                 ` déplace sur le premier élément
  while a[] <> nil          ` teste si la fin de liste est atteinte
    print a[]               ` affiche l'élément actuellement pointé
    a.inc()                 ` déplace sur l'élément suivant
  /while

In descending order:

  a.end()
  while a[] <> nil
    print a[]
    a.dec()
  /while

Use array as stack

After creating a table, you can apply various list or stack functions...

a.push("item")     ...ajoute un élément à la fin de la liste
a.unshift("item")  ...ajoute un élément au début de la liste
a.pop()            ...lit et enlève le dernier élement
a.shift()          ...lit et enlève le premier élement

Thus, you can read and delete table elements using the following statements:
print a.shift ()

Interval in table

The interval is limited to the position interval .

a[pos..fin]           la rangée entre "pos" et "fin" inclus.
a[..fin]              du début jusqu'à la position "fin".
a[pos..]              de la position "pos" à la fin du tableau.
a[..]                 prend le tableau entier (peu utile).
a[pos..fin] = nil     supprime une rangée d'éléments.
a[pos..fin] = b     remplace une rangée par un tableau/élément (id).

Array operators

You can add or remove an element or group of elements with the + and - operators.

Example:

array a = ["un", "deux"]
array b
b = a + ["trois", "quatre"]    maintenant le contenu de b est de quatre éléments.
a = b - ["un", "quatre"]       maintenant le contenu de a est: ("deux", "trois").

Only arithmetic operators + and - with the membership operator "in" can be used on arrays.

Operator "in"

This statement can be used to check whether a value is in the list (array, dictation or even text), as well as to view the content.

Syntax and examples:

if variable in array
for variable in array

if x in a :   print "dedans";  /if
if x in [1,2,3] : print "dedans"; /if
for x in a print x
for t in ["un", "deux", "trois"]  print t

Binary dynamic list operators

In dynamic lists (array or dict), you can use binary intersection and union operators. The intersection of two lists returns only those items that are both included in both lists. Combining two lists is a new list consisting of elements of the first, plus those from the second minus those who are already in the first.

&  intersection
|  union
^  complément d'intersection

a = [1, 2, 3, 4] & [3, 4, 5, 6]   fait que a contient (3, 4)..
a = [1, 2, 3, 4] | [3, 4, 5, 6]   fait que a contient (1, 2, 3, 4, 5, 6).

Applying a Function to an Array

The map method, implemented in JavaScript and PHP, allows you to sequentially apply the function to each element of the array and possibly return a new array. Example:

int mapfun(int x) return x * 25

b = [1,2,3,4,5]
print b.map(mapfun)

If you want to apply the function to several arrays at once, or to dictants, you use an index. Example:

for text k, var v in d1
  d1[k] + d2[k]
/for  

The contents of the associative array d2-d1 are added for each element.

Using the function, has two parameters:

array d1 = [1,2,3,4,5]
array d2 = [10, 20, 30, 40, 50]
int mapfun(int x, int y) return x + y
for int i, var x in b print mapfun(d1[i], d2[i])

Multidimensional table

The number of measurements is not limited. For a two-dimensional table, the syntax for...
- access to element: x = nomarray [i] [j]
- change element: nomarray [i] [j] = x
To create an element, the syntax is:

  nomarray[i] = []
  nomarray[i][j] = x
  ou
  nomarray[i] = [x]

You cannot create an element directly in a subordinate array that does not exist. The indices i and j assume that i and j elements already exist.

Comparison of two tables

The language can make comparisons between arrays of numbers with all relational operators. Two tables of different sizes are considered.

You can check between two text tables or other objects whether they are identical or different. For other comparisons, you need to define your own algorithm.

Table content in PHP, step by step

We need to know how whole array keys in PHP change depending on the operations that can be performed. This is important for understanding associative tables and avoiding many errors.
Content is displayed after each operation.

  array a = []
  array ()

  a.push("un")
  array
  (
   [0]=> un
  )

  a + [ "deux", "trois", "quatre" ]
  array
  (
   [0]=> un
   [1]=> deux
   [2]=> trois
   [3]=> quatre
  )

  a.shift()       ... le premier élément est supprimé et les clés sont renumérotées.
  array
  (
   [0]=> deux
   [1]=> trois
   [2]=> quatre
  )

  a[1000] = "mille"
  array
  (
   [0]=> deux
   [1]=> trois
   [2]=> quatre
   [1000]=> mille
  )

  a.unshift("x")       ... toutes les clés sont renumérotées, même la clé 1000.
  array
  (
   [0]=> x
   [1]=> deux
   [2]=> trois
   [3]=> quatre
   [4]=> mille
  )

 Créons deux nouveaux tableaux:
  array a = [ "un","deux" ]
  array b = []
  b[1000] = "mille"
  a + b
  Les clés sont renumérotées.
  array
  (
   [0]=> un
   [1]=> deux
   [2]=> mille
  )

If you replace a + b with a.push ("thousand"), the result is the same.

Array methods

Iterators are not yet implemented by the JavaScript compiler, nor are begin, dec, etc. methods recognized.

Retour  Nom               Action

var     begin()           pointe sur le premier élément.
var     dec()             retourne un élément et décrémente le pointeur.
void    display()         affiche le tableau.
var     end()             pointe sur le dernier élément.
bool    empty()           return true si le tableau est vide.
int     find(var)         recherche un élément, retourne l'index ou nil.
int     findLast(var)     recherche un élément à partir de la fin.
var     inc()             retourne un élément et incrémente le pointeur.
int     index()           retourne l'index de l'élément pointé.
void    insert(int, var)  insère un élément à un index entier (pas un text).
text    join(text sep)    convertit en text avec le séparateur donné.
text    key()             retourne la clé de l'élément pointé.
bool    load(text nom)    charge un fichier dans un tableau ("file" de PHP).
var     min()             retourne la valeur la plus faible.
var     max()             retourne la plus forte valeur.
array map(fonction) applique une fonction à chaque élément et retourne un nouveau tableau. void pack() rend les éléments du tableau consécutifs. var pop() lit et supprime le dernier élément. var pop(int) lit et supprime l'élément à la position donnée. void push(val) ajoute un élément à la fin. var rand() retourne un élément à une position aléatoire. array reverse() retourne la liste en ordre inversé. var shift() lit et supprime le premier élément. int size() retourne le nombre d'éléments. void sort(int) trie les valeurs en ordre ascendant. void rsort(int) trie les valeurs en ordre descendant. void store(text nom) sauve le tableau dans un fichier. Ajouter false en argument pour ne pas ajouter de code eol. number sum() calcule la somme des éléments. text toText([text]) convertit le tableau en chaîne avec code de séparation en option. array unique() retourne le tableau sans valeur en double, la première est gardée. void unshift(var) insère un élément en première position.

The method exits the array with an optional parameter: 0 for alphanumeric classification (default in JavaScript and PHP), 1 for numeric classification.

Dictionary

Dictation is a smoke list of key and valuable couples. Keys are always texts. Values can be any object.
The key and value can be variable. Key pair format and values:

clé:valeur

An empty dictation is represented as {}. A literal dictation is a list of pairs separated by a comma and bent between {}.

Instead of a table, a dictation is created by agendas:

d[k] = "b"
d["un"] = "element 1"

Even if JavaScript supports numeric keys enclosed in quotation marks, so considered as texts, this leads to unpredictable results when mixed with letter keys. So you have to avoid blending guys.

Create Dictionary

You can create a dictation from a literal or constructor.

Syntax:

dict d                                 // crée un dict.
dict d = {x:v, y:w,...}                // crée et initialise un dict.
dict d = {}                            // crée un dict vide.

Values can be any object type.
The key can be a variable and the value can be an expression.

Example:

text k = "a"
text v = "b"
dict d = {k : v}
dict d = {k : v + "x".dup(4) + 20.toText()}

This example writes in dict d "ball 20" with key "a."

Index Dictation

Values ​ ​ in the dictation are available with a text key.

Syntax:

  d["clé"]              prend le premier élément avec la clé "clé".
  d[clé] = valeur       remplace une valeur ou ajoute un couple
                        clé-valeur si la clé n'est pas déja dans le dict.
  d[clé] = nil          supprime un élément.
  d = {}                efface le dict.

Exemple:

  dict d
  d["program"] = "ce que l'on veut accélerer"
  print d["program"]                   affiche le texte ci-dessus.

Interval in diktat

The usual way to use the dictionary is with keys or iterators. In some cases, direct access to a range of values may be useful.
- When adding an element or other dictation to the dictation, using intervals, push, unshift, PHP generates a new key for this element. The new key is a number.
- If you replace the interval with another dictation, some elements may be lost. This also happens when merging.
- Keys of the dictation replacing the interval are not saved.

Display views:
He must present all the keys and values ​ ​ in dictation.

  dict d = {"a":"alia", "b":"beatrix", "c":"claudia"}  

  d.display()                     

  for k,v in d : print k, v; /for

Dictation methods

Retour  Nom               Action

void    display([flat])   affiche le dict indenté. Si l'argument est false, il n'est pas indenté.
bool    empty()           retourne true si le tableau est vide.
int     hasKey(text)      retourne true si la clé existe.
int     find(var)         recherche un élément, retourne l'index ou nil.
dict    getById(text)     retourne un dictionnaire assigné à la propriété en paramètre.
array   getByName(text)   retourne la liste des éléments dont l'attribut name a l'argument pour valeur.
array   getByTag(text)    retourne la liste des objets donc l'attribut tag à l'argument pour valeur.
array   keys()            retourne la liste des clés.
void    kSort()           réordonne les index en préservant les associations.
void    load(text nom, [xml])    charge un fichier dans le dict. 
var     pop()             lit et supprime le dernier élément.
var     shift()           lit et supprime le premier élément.
int     size()            retourne le nombre d'éléments.
void    sort(int, bool)   trie les valeurs en ordre ascendant.
void    store(text nom)   sauve le dict dans un fichier.
text    toXML()           convertit le dict en fichier XML dans une chaîne.
void    unshift(text,var) insère une paire clé valeur première position.
array   values()          retourne la liste des valeurs.

Load method: A file is converted from XML to dict if it has the extension xml, rss, svg, or if the optional argument is 1.

Typical tables

The typed table contains a unique object type. This is much more efficient than a general table because it is indexed rather than associative, and contains directly 32 or 64-bit objects or pointers rather than dynamic objects (var).
An array of integers is 100 times faster than the standard array for binary executables, but there is no difference in PHP.
Typed tables are also dynamic, and size is not predefined or constrained.

Builder and literal

The conspirator of a typical picture has the form:

type(...éléments...)

Exemple:

int(1, 2, 3)

Number of elements from 0 to n.

If there is one element, there is no difference between a typical array constructor and a scalar constructor:

  int(1)
  real(10r)

This is not a problem when assigning, since you can create a singleton array from a scalar array.

Table of integers

The syntax for declaring an array of integers is:

  int[] i = int(x, y, ....)

Once declared, it is used as a mixed array, but only integers can be added to it.
When creating, you can assign a constructor or a literal.
A singleton constructor is equivalent to an integer constructor. You will have to use a literal in one expression.

Examples:

  int[] x = int(5)
  int[] x = int(1,2)
  int[] x = y + int{5}

Table of real, natural, numbers

Applications:

  real[] r    = real(1.0, 2.0, etc...)
  natural[] n = natural(1, 2, etc...)
  number[] n  = number(1, 2.0, ...)

Text table

The declaration has the form:

 text[] t = text("un", "deux", etc...)

Purpose and conversion

For a mixed array, you can only assign using the arrayval function:
Example:

  int[] i = int(...)
  array a = arrayval(i)

But you can only create a mixed picture with a typical constructor:

Examples:

    [1,2,3]           ... c'est un tableau mixte, avec des éléments entiers
    int[] i = [1,2,3]     ... NON VALIDE, il faut plutôt écrire:
    int[] i = int(1,2,3)  ... valide.

Examples:

  array a = int(1,2)          ... NON valide
  array a = [ int(1,2) ]       ... NON valide

Typical table and var

A typical table can be assigned to a var.

  int[] i = int(1,2)
  var d = var(i)

There are two methods for using this var:
arrayType () returns the array type contained in var.
toList (int = 0) returns a typical content array.
The parameter is a type and is required when var contains a mixed table that needs to be converted to a typical table.

Recognized types:

  $TYPE_INT        tableau d'entiers
  $TYPE_REAL
  $TYPE_NATURAL
  $TYPE_NUMBER

Example:

  d = var(int(1,2))
  if d.arrayType()
  = $TYPE_INT:
     int[] i = d.toList()
  = $TYPE_REAL:
     real[] r = d.toList()
  /if

Direct assignment

For PHP compatibility, adding an element to an array larger than the current size has the same effect as adding this element, regardless of the specified index.
Exempli gratia:

 int[] i = nil
 i[10] = 10                         équivaut à:  i.push(10)

Adding values ​ ​ is the correct way to fill the table.

If we really want to put an element in a given position, we must fill the table with zero values...

 for int k in 0 .. 10 let i.push(0)

You can now place the item at position 10.

Limitations and compatibility

- The method cannot be applied directly to the specified element.

  i[10].toText()    .. non valide
  int x = i[10]
  x.toText()         .. valide

- The PHP function "array_diff" does not work when the array contains objects, so it is impossible to subtract such arrays.

Row

A file is a virtual object for processing local or remote files.
For a complete explanation of the file system, see "fopen" in the C or PHP manual.
A queue object is created by declaring an instance of a queue type. The file on disk is created with the open command. It provides access to the file in various modes, depending on the second parameter of the method.
The error control structure allows you to check whether the file was opened correctly or not.

Syntax for creating or opening a file:

  file nomfic                 declare un file.
  nomfic.open(path, mode)     ouvre un fichier selon un chemin et un mode.

Types de chemins:
  http://path                    fichier distant http.
  ftp://path                      fichier distant ftp.
  path                             fichier local.

Modes:
  "r"            lecture seulement, à partir du début.
  "w"            écriture  seulement à partir du début.
  "r+"           lecture ou écriture au début du fichier.
  "a"            ajout en fin de fichier en écriture seule.
  "a+"           lecture à la position courante, ou écriture à la fin.

File methods:

retour     méthode                  action

int        eof()                    retourne true quand la fin de fichier est atteinte.
int        open(text, text)         crée ou ouvre un fichier. Positionne le drapeau "error".
int        close()                  ferme le fichier.
text       read(int)                lit un bloc selon la taille en argument, retourne un text.
text       readLine()               lit et retourne la ligne suivante dans un fichier de texte.
int        seek(int)                va à la position donnée en argument, retourne 1 si ok.
int        size()                    retourne la taille du fichier.
int        time()                   retourne la date de dernière modification.
int        write(text)              écrit le texte donné en argument, retourne la taille écrite.
void       writeLine(text)         écrit le texte en argument.

Examples:

file nomfic                       crée un objet file.
nomfic.open("monfichier", "r")        ouvre un fichier physique.
nomfic.close()                    ferme le file.
bool b = nomfic.eof()         assigne vrai à b si la fin de fichier est atteint.
nomfic.seek(250)                 lecture ou écriture en sautant 250 octets.

Deleted files are not currently managed by Scripting C and the interpreter.

Reading

The file can be read by lines or by binary blocks.
In the first case, the readLine () method is used, otherwise the read method is used with the block size in the arguments.
The line terminator in the file is included and can be removed by the rTrim () method.

Examples:

text t = nomfic.readLine()            lecture d'une ligne de texte.
text t = nomfic.read(1000)           lecture de 1000 octets.

Write

The write method places the contents of the text variable in a file. After opening the file in "w" or "a" mode and saving either from scratch or at the end of the current content, each new write call adds new text to the end.

A simple example:

text nomfic = "monfic"                 // nom du fichier
file sortie                                  // nom de l'objet virtuel
sortie.open(nomfic, "w")               // ouvert en écriture
error? die("impossible d'ouvrir " + nomfic)
for text ligne in maliste              // un tableau quelconque
   sortie.write(ligne)                  // enregistrer un élément
/for
sortie.close()                         // fermer le fichier

XML

You can insert standard XML code into the scripting program. It will be converted to an associative table. A tag contained in another tag is converted to dictation as an element of another dictation.

The text content of the tag is associated with the data key in the generated associative table.

Example:

<xml id="car" speed=150 name="Spitfire">
<engine id="engine1" power=100 />
<passengers id="pass1" num=4 >
"Clara, Dana, Elisa, Farah"
</passengers>
</xml>

This JavaScript code is generated by the compiler:

var car={
  "_00" : "car",
  "tag" : "xml",
  "speed":150,
  "name":"Spitfire",
  "engine1":{
    "tag": "engine",
    "power":100
  },
  "pass1":{
    "tag": "passengers",
    "num":4,
    "data":"Clara, Dana, Elisa, Farah"
  }
};

Or this PHP code:

$car=[
  "speed"=>150,
  "name"=>"Spitfire",
"engine"=>[ "power"=>100 ],
"passengers"=>[ "num"=>4,
"data"=>"Clara, Dana, Elisa, Farah" ] ];

An associative table can also be converted to an XML document in a text variable that can be saved in a file:

car.toXML().store("fichier.xml")

Control structure error

After an open statement, the error .../error constructor must be executed in the event of an access error. But the interpreter can stop the program before reaching the design. Otherwise, the contents of the block will be executed in the event of an error.

Syntax:

xxx.open("nom fichier")
error
      ...instructions...
/error
ou:
  xxx.open("nom fichier"); error ? action
ou:
  xxx.open("nom fichier"); error action

Example:

file monfic
monfic.open("nom", "r")
error? exit()

If the file is not found or cannot be opened, the program stops.

Areas

Visibility rules refer to basic procedural languages, not scripting languages.
Scriptol adds security rules, it does not allow you to assign the same name to two objects in nested areas (for example, in the global scope and function). But the same names can be repeated in consecutive places.

There are four levels of visibility: - global, - class, - function body, - and the body of the control structure.

The visibility of a variable is the level at which it is declared: Global, class, function or restricted block (if, do, for, etc.), as well as content levels.

You cannot re-write a variable where it remains visible. It can be re-declared only if its area is closed, within sequential functions or control structures.

The assembly header for is part of the block area.

for text t in a                 // t est visible seulement dans la boucle for.
   t = a.inc()
/for

The portion of let that terminates the while loop is in the loop area .
Function arguments are in the scope of the function.
Within a function, if a variable references before assignment, it references a global variable if it exists, otherwise it is an error.
In a class method, if it is mentioned before assignment, it refers to an attribute if it exists, otherwise it is an error.
Global variables are not visible in the class except external variables.

External variables (from PHP, Apache, etc.) are always in the zone, since there is no control over them. Therefore, you must know their name so as not to reuse it, since Script variables turn into a PHP variable with $ in front.
When using external variables in a function, they must be declared "global," since the compiler does not manage them.

External variables, constants, and functions

Variables and constants

PHP variables and constants can be used as Script variables and constants when declared with the keyword "exter."
External announcements, like included ones, are placed in the file header.

Syntax for external variable:

  extern type identifieur
  extern const type identifieur

No external object type or scope checks. The function requires a "global" statement.

Example:

  global argv
  array a = $argv

The PHP constant is declared as a variable with the const keyword:

   extern const text PHP_VERSION
    ...
   print PHP_VERSION

You can also use a PHP or C++ variable without an announcement with the prefix $ followed by an identifier.
It can start with an underscore.

  $var_name
  $(constant_name)                          in PHP
  $constant_name.                           in C++

External functions

PHP functions can be used without declaration, which does not happen with C++ functions.
They can also be declared the exter keyword. The default value is determined by the destination. This value is used in C++, it is ignored by PHP.

Syntax and example:

  extern type identifieur(... arguments...)
  extern text substr(text, int, int = 0)

External class

To use PHP or C++ class methods, you must declare these classes and the elements you want to use.

Example:

extern
  class phpClass
     int phpAttribute
     void phpMethod(int argument)
     ... déclaration ...
  /class
/extern

External types

C++ allows you to define types with "typedef" and "# define" directives. These new types can be integrated with the selected Script statement.
Example: define uint
This corresponds to "# define uint unsigned int" in C++.
No code is generated by define: C++ code must be in the C++ file to be included. See the "Instruction Malfunction" section for details.

Insert Target Code

If you want to insert the target code directly into the program, use ~~ characters to determine the beginning and end of the included code.
The compiler ignores the content as if it were comments, but includes it in the generated code, PHP, JavaScript, or C++.

The @ code is used for a simple identifier or reserved word. Example:

@await 

You can insert specific PHP or C++ code into one program. To insert PHP code, use:

require_once("lecode.php")

This statement has an effect only for a PHP interpreter compiled in C++, it is ignored.

To insert C++ or JavaScript code, use:

include "lecode.hpp"
include "lecode.js"

Class

A class is a structure that contains variables (attributes) and has functions (methods).
Once a class is defined, it becomes the new complex language type by which objects, instances of the class, are declared. Object attributes and methods are used with the figure command:

  x = objet.attribut
  objet.methode()

Class definition

The class description begins with the keyword "class" and ends with "/class. "

Attributes (variables) must be placed before elements. The class opens a scope. Global variables and defined functions are not visible within the class. The attributes and methods of a class or instance of another class are visible in all methods of the class with the instance name in the prefix.

Example of a class declaration:

class voiture
     ...membres...
  /class

Example class with attributes and methods:

class voiture
      int lavitesse = 50
      int passagers = 4

      void voiture.vitesse(int i)
          int x = lavitesse * 2
      return x
  /class

Example instance with method reference:

voiture mavoiture
print mavoiture.passagers
print mavoiture.vitesse()

Constructor and Instance

A constructor is a method with a class name that is called when an instance of a class is created.
He always has a return type of "void," which means: nothing.

Example constructor:

  class Voiture
      int vitesse

      void Voiture(int p)          // cette méthode est un constructeur
         vitesse = 0               //vitesse est initialisée lors de la déclaration d'une instance
      return
  /class

Syntax for instantiating:
Nomclasse nomstance = Nomclasse (argument [, arguments])
or:
Name class for constructor with no arguments

Example:

  Voiture mavoiture = Voiture(60)               ... crée une voiture avec une vitesse de 60
  Camion moncamion                      ... equivalent à ci-dessous
  Camion moncamion = Camion()

Static Methods and Attributes

It may be convenient to collect all functions related to the task into one class and declare them "static." You can call these functions directly with the class name without having to create an instance.

Example:

  node, ext = Dir.splitExt(chemin)

Attributes can also be static. A static attribute is common to all inherited instances. A static method cannot reference attributes because they exist only in instances of the class unless they are also static.
Another method cannot be called in the body of a static method.
The keyword "static" must precede the object type.
An error message is issued when a static function uses a non-static attribute or calls another method.

Example of static attributes and methods:

  class Voiture
    static usine = "Xxx"
    static void denomme(text x)
      usine = x
    return
  /class

  Voiture.denomme("nom")
  Voiture.usine = "nom"

Static attributes and methods can also be associated with an instance:

  Voiture maVoiture
  maVoiture.denomme("nom")
  maVoiture.usine = "nom"

The effect will be the same.

Inheritance

A class can inherit attributes and methods from another class if it is declared a subclass of another class.
The name class inherits the attributes and methods of "Austrian." It also works with static attributes and methods.

Inheritance declaration syntax:

  class nom is autrenom

Example:

  class Vehicule
    int fuel
    void Vehicule()
     fuel = 100
    return
  /class

  class Voiture is Vehicule
    int passagers
    void Voiture()
       passagers = 3
       fuel = 50
    return
  /class

  class Camion is Vehicule
    int charge
    void Camion()
      fuel = 200
      charge = 1000
     return
 /class

  Camion bibendum
  Voiture daisy
  print bibendum.charge         attribut de la classe Camion
  print bibendum.fuel             attribut de la superclasse Vehicule
  print bibendum.passagers     mauvais! passagers non accessible à Camion!
  print daisy.passagers          bon, passagers est attribut de Voiture

Overload

The method can be overridden with different arguments, both in the same class and in derived classes. Return type of all method versions must be the same.

Example:

  void ajoute(int x, int y)
  void ajoute(real x, natural y)

You just need to call the "add" method with the desired type of arguments, the compiler associates the corresponding definition...
The target C++ language requires that overloaded methods have the same return type that Script stores.

Async/await (JavaScript)

Syntax:

async type nomfonction(paramètres)
  var x = await autrefonction(arguments)
     ... instructions suivantes...
return

Example:

int fibo(int n) 
   if (n < 2) return n
return fibo(n-2) + fibo(n-1)

async void getFibo(int n) 
  int f = await fibo(n)
  print "fibo=",f
return 

getFibo(20)

Dans la fonction déclarée async, les instructions qui suivent l'appel déclaré await, ne sont exécutées qu'après que cette dernière ait retourné une valeur, même si elle est asynchrone.

Par contre les instructions qui suivent l'appel de la fonction async, sont exécutées immédiatement sans attendre.

Dans le but d'éviter des confusions il est préférable que la fonction async ne retourne pas de valeur, même si cela serait néanmoins correct et accepté par le compilateur.

Le compilateur encapsule l'appel de la fonction qui suit await dans un objet Promise. Si la fonction appelée retourne déjà un objet Promise, alors on utilisera plutôt:

@await 

Include, import et require

La syntaxe pour inclure un fichier externe est:

include "nomfichier.sol"

Les parenthèses sont optionnelles. Les guillemets simples ou doubles sont requis. Si vous voulez utiliser directement un fichier PHP, et que le compilateur ne le traite pas, utilisez l'extension PHP.
Seuls les fichiers avec l'extension ".sol" seront traités par les compilateur, si elle est différente:

Examples:

include "exemple.php"
include "exemple.js

Le fichier PHP sera ignoré par le code JavaScript et le fichier JS sera ignoré par le code PHP.

Quand du code scriptol est inséré dans une page HTML, le contenu d'un fichier à inclure doit être placé à l'intérieur des balises <scriptol> et </scriptol>, même si le fichier ne contient que du code scriptol. Le code généré pour une page HTML peut être différent.

Utiliser un module externe (JavaScript)

Les modules externes inclus par npm peuvent être déclaré comme dictionnaire ou comme objet.

Dans le premier cas on déclare le module ainsi:

const net = require("net")

Dans le second cas, le module doit être importé avec la commande import:

import MyModule = require("MyModule")

Et dans le second cas, cela doit être utilise par une instance:

MyModule module1

Dans tous les cas le compilateur n'effectue aucun contrôle sur les attributs, méthodes et arguments. Cela est délégué à la machine virtuelle JavaScript.

Utiliser une fonction comme argument

Vous pouvez utiliser une fonction comme argument d'une autre fonction en la définissant en tant que type. Cela ne fonctionne qu'au niveau global et pas dans une classe. Une fois un type défini, on ne peut le redéfinir.

1) définir une fonction:
Exemple:

  int compare(int a, int b)
    bool b = (a < b)
  return b

2) Utiliser le type function comme argument:

  void mafonc(function a, int x, int y)
    print a(x,y)
  return

3) utiliser la fonction générique:
L'argument peut être la fonction originelle ou une autre fonction avec mêmes arguments et même types de retour.

  mafonc(compare, 10, 8)

Utiliser un type externe

La syntaxe:
define NOUVEAUTYPE
define NOUVEAUTYPE as
crée un nouveau type que l'on peut utiliser en argument de fonctions externes.
Le modificateur "as" fait que le nouveau type ne peut être un pointeur. Donc on l'utilise comme une primitive, comme uint ou gint par exemple.

Fonctions usuelles

Ces fonctions sont communes à PHP, C, C++ et . Si le nom PHP diffère, il est donné dans la liste.

La liste complète est dans le fichier fun.hpp.

void die(text message)       Affiche un message en quittant le programme.
void exit()                  Quitte le programme. Peut afficher un message.
number min(number, number)   Retourne le plus petit de deux scalaires.
number max(number, number)   Retourne le plus grand de deux scalaires.
const cstring plural(int x)  Retourne le pluriel "s" si le nombre x > 0.
array range(int x, int y)    Génère un tableau des entiers compris entre x et y.
cstring str(number)          Convertit un nombre en chaîne de charactères.
void swap(var, var)          Echange le contenu de deux variables.
text pad(text t, len l , text c  [, int o]])
  Complète un texte avec des espaces ou la chaîne de caractères donnée.
  t: text à compléter.     l: longueur à atteindre.
  c: texte à ajouter, des espaces par défaut.
  o: option STR_PAD_LEFT, STR_PAD_BOTH, par défaut à droite. (Voir: str_pad)

Casting

text chr(integer)              Retourne le charactère pour une valeur ASCII.
                               Ex: chr(32) retourne un espace blanc.
int ord(text)                  Retourne la valeur ASCII d'un charactère.
int intval(any)
int realval(any)
natural naturalval(any) 
text strval(any)               Convertit un nombre en text. 
char *str(any)                 Convertit un nombre en chaîne de charactères C. 
bool boolval(int) 

array arrayval(tarray)         Convertit un tableau typé en tableau d'objets dynamiques.

Fonctions de fichiers (voir aussi les méthodes du type File):

void exec(text)               	Passe une commande au système d'exploitation.
bool file_exists(text)     	Teste si le fichier dont le nom est en argument existe.
number filesize(text)         	Retourne la taille.
number filetime(text)         	Retourne la taille (utiliser la fonction date pour afficher).
text filetype(text)           	Retourne "dir" ou "file".
text fileToText(text)          Charge un fichier et retourne un texte.
bool rename(text, text)    	Renomme un fichier. Retourne faux en cas d'échec.
void system(text commande)    	Passe une commande au système d'exploitation.
bool unlink(text)          	Efface un fichier. Retourne true si effacé.
var require(text)             	Déclare un module externe (JavaScript seulement).

Fonctions de répertoire:

bool chdir(text)          		Change le répertoire courant. Retourne false si échec.
bool mkdir(text)          		Crée un sous-répertoire. Retourne true si créé.
bool rmdir(text)          		Efface un sous-répertoire. Retourne true si éffacé.
text getcwd()                	Retourne le chemin répertoire courant.

Fonctions mathématiques:

number abs(number)          	Retourne la valeur absolue d'un nombre.
real acos(real)
real asin(real)
real atan(real)
number ceil(number)         	Retourne le nombre arrondi à l'entier supérieur.
real cos(real)
real exp(real)
number floor(number)        	Retourne le nombre arrondit à l'entier inférieur.
number fmod(number, number) 	Return le modulo de deux nombres.
real log(real)
number pow(number, number)  	Retourne la puissance n d'un nombre.
int rand()            			Retourne un nombre aléatoire.
void randomize()        		Démarre une séquence de nombres aléatoires.
real round(real)       		Arrondi au plus proche, plancher ou plafond.
real sin(real)
number sqrt(number)         	Retourne la racine d'un nombre.
real tan(real)

Fonctions de temps:

int time()           			Temps en millisecondes depuis le 1 Janvier 1970.
dict localtime()       		Temps et date courant lors de l'appel, dans un dictionaire, voir ci-dessous.

Clé du dict retourné par localtime:

tm_sec     Secondes après la minute	[0,61]
tm_min     Minutes après l'heure    	[0,59]
tm_hour    Heures après minuit      	[0,23]
tm_mday    Jour du mois          		[1,31]
tm_mon      Mois à partir de Janvier   [0,11]

tm_year     Année depuis 1900
tm_wday     Jour à partir de Dimanche  [0,6]
tm_yday     Jour depuis le 1 Janvier   [0,365]
tm_isdst    Indicateur d'heure d'hivers

Gestion des exceptions

Le traitement des exceptions requiert une définition externe. Syntaxe:

  extern
     class exception
       string what()
     /class
  /extern

  try
     ... quelques instructions ...
  catch(exception e)
     print e.what()
  /try

Extensions JavaScript

Lorsqu'il est compilé en JavaScript, le langage offre des fonctions supplémentaires. Elle sont décrite sur le site du langage.

Appendice: mots-clés

Des mots peuvent être réservés pour le langage cible mais ne font pas partie de .

alias always and array await as async
bool bool break byte
case catch char class const continue
define dict do
echo else enum error exception
false file finally float for forever from function
global
if import in include int integer is
let long
mod
nan natural new nil not null number
or
print private protected public
react real require return
script scriptol sol static step super switch
text this to true try
undefined until
var void
while
yield
zero


© 2001-2021 Denis Suro.