BEE maintains a separate context (variable name space) for the life-time of a function execution. You can define new variables within a function without affecting those in the caller script. These new variables, which are accessible only from within the function, are said to be in the "local" context. Upon the function exit, the local context will be destroyed. (System classes and some special variables are not in the local context and can survive the function exit.)
If the function is called from another function, to the callee function, the context of the caller function is called the "parent" context. The context of the main script is called the "global" context.
Look at this example of bean counting. The variable "numBeans" is global.
function count_beans {
global numBeans;
if ({arg%beans|isset}) var numBeans conv="+=:{arg%beans}";
}
var numBeans = 0;
count_beans beans=3;
count_beans beans=5;
display "{numBeans}"; // Output: 8
Now we make it capable of counting "array of bean trays", just to illustrate the idea of using the parent scope.
function count_array {
parent total;
var total = 0;
if ({arg%arr|isset}) foreach (arg%arr) var total conv="+=:{foreach}";
}
function count_beans {
global numBeans;
if ({arg%beans|isset}) {
count_array arr="(var)arg%beans";
var numBeans conv="+=:{total}";
}
}
var numBeans = 0;
count_beans beans=3;
count_beans beans="(array)5,9,11";
display "{numBeans}"; // Output: 28
Note: The parent or global linked variable can be initialised in either the caller or the callee function. Though not compulsory, it is recommended to initialise a variable before use.
A programming hints: To make your program more robust against structural re-organisation, always use "parent" link unless you are sure the linked variable is in the "global" context.
|