Node:prolog_event, Next:, Previous:Evaluate a Tcl expression and get Prolog events, Up:Event functions



Adding events to the Prolog event queue

The Tcl interpreters under the SICStus Prolog library are extended with a command, prolog_event, for adding events to a Prolog event queue.

The prolog_event command has the following form:

   prolog_event Terms ...

where Terms are strings that contain the printed representation of Prolog terms. These are stored in a queue and retrieved as Prolog terms by tcl_event/3 or tk_next_event/[2,3] (described above).

An example of using the prolog_event command:

test_event(Event) :-
    tcl_new(Interp),
    tcl_event(Interp, [prolog_event, dq(write(zap(42)))], Event),
    tcl_delete(Interp).

with the query:

| ?- test_event(Event).

will succeed, binding Event to the list [zap(42)].

This is because tcl_event converts its argument using the special Command Format conversion (see Command Format) which yields the Tcl command prolog_event "zap(42)". This command is evaluated in the Tcl interpreter referenced by the variable Interp. The effect of the command is to take the string given as argument to prolog_event (in this case "zap(42)") and to place it on the Tcl to Prolog event queue. The final action of a tcl_event/3 call is to pick up any strings on the Prolog queue from Tcl, add a trailing full stop and space to each string, and parse them as Prolog terms, binding Event to the list of values, which in this case is the singleton list [zap(42)]. (The queue is a list the elements of which are terms put there through calls to prolog_event).

If any of the Term-s in the list of arguments to prolog_event is not a valid representation of a Prolog term, then an exception is raised in Prolog when it is converted from the Tcl string to the Prolog term using read. To ensure that Prolog will be able to read the term correctly it is better to always use write_canonical and to ensure that Tcl is not confused by special characters in the printed representation of the prolog term it is best to wrap the list with list.

A safer variant that safely passes any term from Prolog via Tcl and back to Prolog is thus:

test_event(Term, Event) :-
    tcl_new(Interp),
    tcl_event(Interp, list([prolog_event, write_canonical(Term)]), Event),
    tcl_delete(Interp).