Standard Variables

 

Unlike C/C++, variables in SPL are not declared by type. Simply assigning a value with the = operator creates the variable if it did not previously exist and also establishes its type. Variable names are not case sensitive. A variable may assume any of the following data types:

 

 

a = 10;

// integer

b = 3.14;

// real

c = 1 + 5i;

// complex

d = "This is a string";

// string

h = 0x100;

// integer in hex form

s = {1, 2, 3, 4};

// 4 element series

t = {{1, 2, 3}, {4, 5, 6}};

// 2 x 3 array

 

 

The data type of a variable can be altered by re-assignment.

 

a = 1;

if (max(w1) < 0) a = "Negative Value";

 

Variables used within a user-defined function are local to that function. When the evaluation of the function is completed, the local variables for the function are automatically deleted. The local keyword explicitly declares a local variable.

 

fun1(x)

{

    local a;

 

    a = x + 1;

    return(a);

}

 

Now consider the following interactive session:

 

a = 1

 

fun1(10) returns : 11

 

a returns : 1

 

The variable a referenced in function fun1 does not conflict with the global variable a defined in the session. To explicitly manipulate a global variable within a user-defined function, use the setvar routine or declare the variable as extern.

 

fun2(x)

{

    setvar(a, x + 1); 

    return(a); 

}

 

a = 1

 

fun2(10) returns: 11

 

a returns: 11

 

The fun2 function explicitly gets and sets the value of the global variable a. A global variable can also be specified using the extern or global keyword.

 

fun3(x)

{

    extern a;

 

    a = x + 1;

    return(a);

}

 

Function fun3 performs exactly as fun2 but uses a cleaner, more compact syntax.

 

A static variable behaves exactly like a local variable except a static variable is persistent across function calls.

 

sumval(x)

{

    static sum = 0; 

 

    sum += x;

    return(sum);

}

 

The function sumval returns the sum of the current input value and all previous values. The static variable sum behaves like a local variable except it is persistent from one call to sumval to another.

Static variables can be file based such that all functions within the same SPL file have access to the variable.

 

// sumval.spl

 

static sum = 0;

 

sumval(x)

{

    sum += x;

    return(sum);

}

 

currsum()

{

    return(sum);

}

 

In this case, sumval behaves identically to the previous example and currsum returns the current sum.

Static variables are initialized when the SPL function is first loaded, whether automatically loaded or explicitly loaded. If no initialization value is given, the static variable is initialized to 0.