Driver-scoped variables are accessible from any rule in an ASL script. There are two lifetimes for driver-scoped variables:
-
Static
-
Record
The difference between the two lifetimes depends on where the variable is assigned a value.
The longer lifetime for a driver-scoped variable is static. When a variable is assigned a value at the beginning of an ASL script, before the START rule is executed, it is static. Static variables maintain their value across uses of the START rule or until a new value is assigned. In Example of a variable with a static lifetime, each time the START rule is invoked, the variable retains its value.
In the following example, the script counts the number of lines of data in a file. A variable is assigned to zero at the beginning of the script. The variable’s value is incremented for each line of input. At the end of the script, the value of the variable is printed. In this script, the START rule is invoked five times and the variable is not reset.
ASL Script (static_var.asl): lines=0; START { .. eol } do { lines = lines+1; } EOF do{ print("Number of lines ".lines); } Input: (static_var.txt): line 1 line 2 line 3 line 4 line 5 Output: $ sm_adapter --file=static_var.txt static_var.asl Number of lines 5 $
The shorter lifetime for a driver-scoped variable is record. A driver-scoped variable has a record lifetime when it is assigned a value in a rule. The value of this variable does not change until it is reassigned a value or when the START rule exits. A driver-scoped variable with a record lifetime is undefined each time the START rule exits. In Example of a variable with a record lifetime , each time the START rule is invoked, the variable is undefined.
In the next example, the script demonstrates that driver-scoped variables keep their value until the START rule is invoked. In the script, a variable is assigned when the HI rule runs (x=TRUE). This variable holds its value when the action block of the program is invoked after the HI rule. When the START rule is invoked again, the input fails to match the pattern specified by the HI rule so the alternate rule to HI, the THERE rule, is invoked and the variable is not assigned a value in this rule. When the execution of the script reaches the action block, no variable exists.
ASL Script (record_var.asl): START { print("Starting again") /* print returns TRUE so can be * used outside of a do*/ HI|THERE } do { if (defined(x)) //Tests whether variable exists {print("x is defined");} else {print("x is not defined");} } HI { "hi" eol } do { x=TRUE;} THERE { "there" eol } Input (record_var.txt): hi there Output: $ sm_adapter --file=record_var.txt record_var.asl Starting again x is defined Starting again x is not defined $