When a Prolog call succeeds, it is possible to access the values of its variables. The global Tcl variable var is an array which contains answer bindings of Prolog variables contained in the last goal. This array is indexed by the name of the variable:
If the variable was not bound during the goal, there is no entry in the var array:[eclipse 27]: [user]. p(a, 1). user compiled traceable 52 bytes in 0.00 seconds yes. [eclipse 28]: tclsh. % prolog {p X Y} success % puts "$var(X) $var(Y)" a 1
If necessary, it is possible to test if a variable is set or not:% prolog "var V" success % set var(V) can't read "var(V)": no such variable while executing "set var(V)"
In these examples it was not necessary to declare the var variable as global, because it was accessed outside of any function. When used inside a function, it must be declared as global, even if the Prolog call occurs in the same function:% info exists var(V) 0
[eclipse 5]: tclsh. % proc flag {} {prolog "get_flag A B"; puts "$var(A) $var(B)"} % flag can't read "var(A)": no such variable while executing "puts "$var(A)..." (procedure "flag" line 1) invoked from within "flag" % proc flag {} {global var; prolog "get_flag A B"; puts "$var(A) $var(B)"} % flag all_dynamic off
Important: Do not confuse Prolog and Tcl/Tk variables usage when calling Prolog from Tcl/Tk. Prolog variables appear with the same syntax as in Prolog. When Tcl/Tk variables are used as arguments of Prolog goals, they are preceded by $ to perform Tcl variable substitution, and the list must be formed using double quotes and not braces, otherwise no substitution takes place.