Global variables are associations between names (atoms) and terms. They differ in various ways from storing information using assert/1 or recorda/3.
Both b_setval/2 and nb_setval/2 implicitly create a variable if the referenced name does not already refer to a variable.
Global variables may be initialised from directives to make them available during the program lifetime, but some considerations are necessary for saved states and threads. Saved states do not store global variables, which implies they have to be declared with initialization/1 to recreate them after loading the saved state. Each thread has its own set of global variables, starting with an empty set. Using thread_initialization/1 to define a global variable it will be defined, restored after reloading a saved state and created in all threads that are created after the registration. Finally, global variables can be initialised using the exception hook exception/3. The latter technique is used by CHR (see chapter 7).
[]
is created (the empty list). On backtracking the
assignment is reversed.[]
prior to backtrackable
assignment.demo_nb_linkval :- T = nice(N), ( N = world, nb_linkval(myvar, T), fail ; nb_getval(myvar, V), writeln(V) ).
Global variables have been introduced by various Prolog implementations recently. The implementation of them in SWI-Prolog is based on hProlog by Bart Demoen. In discussion with Bart it was decided that the semantics of hProlog nb_setval/2, which is equivalent to nb_linkval/2, is not acceptable for normal Prolog users as the behaviour is influenced by how built-in predicates that construct terms (read/1, =../2, etc.) are implemented.
GNU-Prolog provides a rich set of global variables, including arrays. Arrays can be implemented easily in SWI-Prolog using functor/3 and setarg/3 due to the unrestricted arity of compound terms.