Evaluating Tcl Expressions from Prolog

Prolog calls Tcl through the predicate tcl_eval/3, which has the following form:

     tcl_eval(+TclInterpreter, +Command, -Result)
     

which causes the interpreter TclInterpreter to evaluate the Tcl command Command and return the result Result. The result is a string (a code-list) that is the usual return string from evaluating a Tcl command. Command is not just a simple Tcl command string (although that is a possibility) but a Tcl command represented as a Prolog term in the special Command Format (see Command Format).

Through tcl_eval/3, Prolog has a method of synchronous communication with an embedded Tcl interpreter and a way of manipulating the state of the interpreter.

An example:

     | ?- tcl_new(Interp), 
          tcl_eval(Interp, 'set x 1', _),
          tcl_eval(Interp, 'incr x', R).
     

which creates a Tcl interpreter the handle of which is stored in the variable Interp. Then variable x is set to the value "1" and then variable x is incremented and the result returned in R as a string. The result will be "2". By evaluating the Tcl commands in separate tcl_eval/3 calls, we show that we are manipulating the state of the Tcl interpreter and that it remembers its state between manipulations.

It is worth mentioning here also that because of the possibility of the Tcl command causing an error to occur in the Tcl interpreter, two new exceptions are added by the tcltk library:

     tcl_error(Goal, Message)
     tk_error(Goal, Message)
     

where Message is a code-list detailing the reason for the exception. Also two new user:portray_message/2 rules are provided so that any such uncaught exceptions are displayed at the Prolog top-level as

     [TCL ERROR: Goal - Message]
     [TK ERROR: Goal - Message]
     

respectively.

These exception conditions can be raised/caught/displayed in the usual way through the built-in predicates raise_exception/3, on_exception/1, and portray_message/2.

As an example, the following Prolog code will raise such an exception:

     | ?- tcl_new(X), tcl_eval(X, 'wilbert', R).
     

which causes a tcl_error/2 exception and prints the following:

     {TCL ERROR: tcl_eval/3 - invalid command name "wilbert"}
     

assuming that there is no command or procedure defined in Tcl called wilbert.