Variables and Variable Scope

Variables in APL may be either global or local:

  • Global - Declared outside functions and function blocks

  • Local - Declared in a function or function block


// Declaration without initialization int myInt1; //Declaration with initialization int myInt2 = 42;

The declaration order of variables is relevant for the initialization in the sense that earlier variables may be used as input to later variables.

Example - Declaration order of global variables



// Legal int f1 = 1; int f2 = f1 + 1; // Illegal! The following will not compile! int f3 = f4 + 1; int f4 = 1;




The scoping rules are as follows:

  • Global variables are available in all functions and blocks. Note that they cannot be accessed from another agent or by an external APL script.

  • All blocks define a separate scope.

  • Any non-anonymous block statement (statements within a {} block) defines a scope.



Example - Scope



int a; //Variable a is global consume { int b; //Variable b is local to the consume block { //anonomous block int c; //Variable c is local to the consume block; } for(int d=0;d<10;d++) { //Variable d is local to the for-loop } }



'Variable hiding' is not allowed. For instance, if a variable  myVar  has been declared in global scope, it is not permitted to declare another variable  myVar  anywhere else in the code. 

Example - 'Variable hiding' is not allowed





 

 

For the built-in function block variables, such as the input variable in the consume block, ‘Variable hiding’ is allowed.

Final Variables

To prevent variables from being changed, the  final  keyword is used:



Persistent Variables

All variables are by default reset between workflow activations. However, if a value of a global variable has to be saved between each activation, the persistent keyword can be used. The variable declaration as follows:

Persistent variables are read from the database between initialize and beginBatch and saved between endBatch and deinitialize. Consequently, any assignment to the persistent variable in initialize only works the first time, once you have a persistent value this will overwrite the value from initialize. Like all other variable types, persistent variable names are unique for each agent within a workflow.