A Guide to the S-Lang Language: Variables

Next Previous Contents

## 6. Variables

As many of the preceeding examples have shown, a variable must be declared before it can be used, otherwise an undefined name error will be generated. A variable is declared using the `variable` keyword, e.g,

> `

>           variable x, y, z;

> `

declares three variables, `x`, `y`, and `z`. This is an example of a variable declaration statement, and like all statements, it must end in a semi-colon.

Variables declared this way are untyped and inherit a type upon assignment. As such, type-checking of function arguments, etc is performed at run-time. For example,

> `

>           x = "This is a string";
>           x = 1.2;
>           x = 3;
>           x = 2i;

> `

results in x being set successively to a string, a float, an integer, and to a complex number (`0+2i`). Any attempt to use a variable before it has acquired a type will result in an uninitialized variable error.

It is legal to put executable code in a variable declaration list. That is,

> `

>           variable x = 1, y = sin (x);

> `

are legal variable declarations. This also provides a convenient way of initializing a variable.

Variables are classified as either global or local. A variable declared inside a function is said to be local and has no meaning outside the function. A variable is said to be global if it was declared outside a function. Global variables are further classified as being `public`, `static`, or `private`, according to the namespace where they were defined. See the chapter on Namespaces for more information about namespaces.

The following global variables are predefined by the language and live in the `public` namespace. They are mainly used as convenience variables:

> `

>           $0 $1 $2 $3 $4 $5 $6 $7 $8 $9

> `

An intrinsic variable is another type of global variable. Such variables have a definite type which cannot be altered. Variables of this type may also be defined to be read-only, or constant variables. An example of an intrinsic variable is `PI` which is a read-only double precision variable with a value of approximately `3.14159265358979323846`.

Next Previous Contents