Global Variable

As we have seen, local variables can only be accessed by the statements in the function body in which the variables are defined, and can be restrictive sometimes. For example, the following code will not work
taylor_sin = x -> x - x^3 / 6 + x^5 / 120;

test_fun = function x -> d
                 d = abs(sin(x) - taylor_sin(x));
                // bad -- taylor_sin is invisible here
           end
since taylor_sin is a local variable in the scope outside the body of test_fun and therefore can not be accessed inside. One solution to this is passing the value of taylor_sin to the function
test_fun = function (x, f1, f2) -> d
                 d = abs(f1(x) - f2(x));
           end
test_fun(1.25, sin, taylor_sin)
     0.0009258624152
However, this may make the function calls more complicated. Sometimes there are certain important data values that many functions need to use and share. It would be convenient to store such a value in a public area that can be accessed inside any function. Such a variable is called a global variable.

The Shang interpreter maintains a global variable that can be accessed anywhere. The name of this global variable is global. It is a structure whose attributes can be used as if they were independent variables. For example, to create and initialize or modify a global variable named volume, one can do

global.volume = 75

To reference a global variable, the keyword and the dot global. can be omitted if the surrounding scope does not have a local variable with the same name. For example

global.taylor_sin = x -> x - x^3 / 6 + x^5 / 120;

test_fun = function x -> d
                 d = abs(sin(x) - taylor_sin(x));
                 /* this will be ok */
           end
test_fun(1.25)
     0.0009258624152
Note that Function definitions are usually stored in global variables. In the case of C and most other programming languages, functions are special structures and are not stored in variables, but are globally accessible. However, global variables that store other forms of data should not be used excessively. They should not be used in place of normal function argument passing. Too many global data will make the program hard to understand and problems hard to diagnosed.

A global variable can have a domain which limits the values that can be assigned to the variable to a set. The domain is optionally declared when the variable is first assigned a value using the keyword in. For example, a global variable defined as follows can only take one of the three values 0, 1, or 2.

global.u = 1 in {0, 1, 2};
After this, a command global.u = 3 will fail and cause an error, since 3 is not in the domain of global.u. Note that domain can only be specified once. If domain is not specified when the variable is created, it has a default domain _ALL, which is the set of everything.

oz 2009-12-22