TrafficScript scripts can access two persistent associative arrays (also known as maps, tables or hash tables).
-
The global array can be accessed using the data.set() and data.get() functions. Data that is set in this array is persistent, and can be read from a later script. This array is of fixed size (the size is defined by the global setting trafficscript!data_size); when it fills up, you cannot add further entries without first removing some. The contents of this global array is shared between all TrafficScript scripts running on the same ZXTM system (including across different CPU cores), but it's not shared between different ZXTMs in the same cluster. If the ZXTM software is restarted, the contents of the array is lost.
-
The connection-local array is unique to an individual connection. Any data stored in that array (using connection.data.set()) can be retrieved by a later TrafficScript script that processes that connection; all data is discarded once the connection completes.
Maintaining the global array
Elements are added and looked up using the data.set() and data.get() functions. Individual elements can be deleted using the data.remove() function.
You can determine the amount of memory in use by the global array using data.getMemoryUsage(), and delete all entries in the array using the data.reset() function. You can delete a subset of the entries using data.reset( "prefix" ).
For example, if you wish to store several different types of data globally, you should use a consistent prefix to start the name of each key. Then, if you need to free memory, you can easily delete all of the data that is stored one particular purpose (for example, a global cache that grows continually, but can safely be deleted and reconstructed if necessary).
Example: An indexed array
You can use the global associative array to create an indexed array named ‘myarray’ as follows:
sub factorial( $n ) {
if( $n == 0 ) return 1;
return $n*factorial( $n-1 );
}
$c = 0;
while( $c <= 10 ) {
$msg = "Did you know that ". $c ."! is ". factorial( $c ) ."?" ;
data.set( "myarray".$c, $msg );
$c++;
}
$msg = "";
$msg .= "Index 5: ".data.get( "myarray5" )."\n";
$msg .= "Index 10: ".data.get( "myarray10" )."\n";
$msg .= "Index 1000: ".data.get( "myarray1000" )."\n";
data.reset( "myarray" );
http.sendResponse( "200 OK", "text/plain", $msg, "" );
Connection-local arrays
The following KnowledgeHub articles give good examples of using connection-local arrays: