The global keyword declares global variable inside user-defined function. Global variable is the variable that is visible/accessible inside the function AND outside the function (at global formula level).
Due to the fact that AFL by default does not require to declare variables the decision whenever given variable is treated as local or global is taken depends on where it is FIRST USED.
You can however force AFL engine to require all variables to be declared using local or global keywords on formula-by-formula basis by placing SetOption("RequireDeclarations", True ); at the top of the formula.
If given identifier appears first INSIDE function definition - then it
is treated as LOCAL variable.
If given identifier appears first OUTSIDE function definition - then it is
treated as GLOBAL variable.
This default behaviour can be however overriden using global and local keywords (introduced in 4.36) - see example 2.
Example (commentary):
k = 4; //
this is GLOBAL variable
function f(
x )
{
z = 3; //
this is LOCAL variable
return z
* x * k; // 'k' here references global variable
k (first used above outside function)
}
z = 5; //
this is GLOBAL variable with the same name as local variable in function f
"The value of z before function call :" + WriteVal(
z );
// Now even if we call function
// the value of our global variable z
// is not affected by function call because
// global variable z and local variable z are separate
and
// arguments are passed by value (not by reference)
"The result of f( z ) = " + WriteVal(
f( z ) );
"The value of z after function call is unchanged
: " + WriteVal(
z );
Example 2: Using local and global keywords to override default visibility rules:
VariableA = 5; //
implict global variable
function Test()
{
local VariableA; //
explicit local variable with the same identifier as global
global VariableB; //
explicit global variable not defined earlier
//
may be used to return more than one value from the function
VariableA = 99;
VariableB = 333;
}
VariableB = 1; //
global variable
"Before function call";
"VariableA = " + VariableA;
"VariableB = " + VariableB;
Test();
"After function call";
"VariableA = " + VariableA
+ " (not affected by function call )";
"VariableB = " + VariableB
+ " (affected by the function call )"