Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 19.  Multiple Interpreters and Safe-Tcl

Command Aliases

A command alias is a command in one interpreter that is implemented by a command in another interpreter. The master interpreter installs command aliases in its slaves. The command to create an alias has the following general form:

interp alias slave cmd1 target cmd2 ?arg arg ...?

This creates cmd1 in slave that is an alias for cmd2 in target. When cmd1 is invoked in slave, cmd2 is invoked in target. The alias mechanism is transparent to the slave. Whatever cmd2 returns, the slave sees as the return value of cmd1. If cmd2 raises an error, the error is propagated to the slave.


Name the current interpreter with {}.

If target is the current interpreter, name it with {}. The empty list is the way to name yourself as the interpreter. This is the most common case, although target can be a different slave. The slave and target can even be the same interpreter.

The arguments to cmd1 are passed to cmd2, after any additional arguments to cmd2 that were specified when the alias was created. These hidden arguments provide a safe way to pass extra arguments to an alias. For example, it is quite common to pass the name of the slave to the alias. In Example 19-3, exit in the interpreter foo is an alias that is implemented in the current interpreter (i.e., {}). When the slave executes exit, the master executes:

interp delete foo
Example 19-3 A command alias for exit.
interp create foo
interp alias foo exit {}interp delete foo
interp eval foo exit
# Child foo is gone.

Alias Introspection

You can query what aliases are defined for a child interpreter. The interp aliases command lists the aliases; the interp alias command can also return the value of an alias, and the interp target command tells you what interpreter implements an alias. These are illustrated in the following examples:

Example 19-4 Querying aliases.
proc Interp_ListAliases {name out} {
   puts $out "Aliases for $name"
   foreach alias [interp aliases $name] {
      puts $out [format "%-20s => (%s) %s" $alias \
             [interp target $name $alias] \
             [interp alias $name $alias]]


Example 19-4 generates output in a human readable format. Example 19-5 generates the aliases as Tcl commands that can be used to re-create them later:

Example 19-5 Dumping aliases as Tcl commands.
proc Interp_DumpAliases {name out} {
   puts $out "# Aliases for $name"
   foreach alias [interp aliases $name] {
      puts $out [format "interp alias %s %s %s %s" \
         $name $alias [list [interp target $name $alias]] \
         [interp alias $name $alias]]

      Previous section   Next section