:- initialization Goal
Declares that Goal is to be run when the file in which the declaration appears is loaded into a running system, or when a stand-alone program or runtime system that contains the file is started up.
Defined as built-in prefix operator, so a simplified
syntax can be used when using
initialization/1 as a directive. See
Callable at any point during compilation of a file. That is, it can be used as a directive, or as part of a goal called at compile-time. The initialization goal will be run as soon as the loading of the file is completed. That is at the end of the load, and notably after all other directives appearing in the file have been run.
save_program/[1,2] save initialization goals in the QOF
file, so that they will run when the qof file is loaded.
Goal is associated with the file loaded, and with a module, if applicable. When a file, or module, is going to be reloaded, all goals earlier installed by that file or in that module, are removed. This is done before the actual load, thus allowing a new initialization Goal to be specified, without creating duplicates.
To understand the examples fully, read the
reference page on
A common case is when the Prolog process at start up should connect itself to an external database. It should also make the connection when the file with the code for the connection is loaded for the first time.
:- volatile db_connection/1. :- initialization my_init. my_init :- ( clause(db_connection(_), _) -> true ; set_up_connection(Connection), assert(db_connection(Connection)) ).
In the above example,
set_up_connection/1 is user defined.
We do not declare
dynamic in the file, since such a declaration would implicitly delete
all clauses of the predicate when the file is reloaded.
It might not always be desirable to have the connection set up the first time the file is loaded, but only when a system is started up (for instance during the debugging of a database application.) This can be achieved with the following code (note that we use the property that a dynamic declaration reinitiliazes/resets the declared predicate):
:- dynamic connect/0. :- volatile db_connection/1. :- initialization my_init. my_init :- ( connect -> set_up_connection(Connection), assert(db_connection(Connection)) ; assert(connect) ).