Updated 2012-07-08 05:41:05 by RLE

MJ - When using Tcl in an embeded setting, it can occur that the embedder has overridden Tcl commands (e.g. puts) while not preserving the original functionallity. For instance on the Tcl chat someone was having a problem, because puts was overridden in such a way that it was not possible to output to channels other than stdout anymore.

In these situations it might be possible that any newly created interpreters will not have these commands overridden and can thus be used to use the original Tcl implementations of these commands.

As a demonstration lets purposely break puts and try to reuse it from a new intepreter
 # break puts
 # don't do this in a Wish console because that uses puts internally, use tclsh

 % proc puts {args} {error broken}
 % puts -nonewline stdout "Does this work?"
 broken

This leaves us with a thoroughly unusable puts. Next to remedy the situation.

Start with creating a new interpreter:
 interp create iputs

Now we can use the newly created interpreter to have access to puts again:
 % set test "\""
 # will error out
 % interp eval iputs puts $test
 missing "
 # use list
 % interp eval iputs [list puts $test]
 "

We now have access to the normal puts again. One thing to keep in mind is that interps do not share any resources by default. One of the resources one can think of is an open file.
 % set f [open c:/temp/test.txt w]
 file9de458
 % interp eval iputs [list puts $f test]
 can not find channel named "file9de458"

This will be a problem when you have to use resources that are opened in the main interpreter. In the general case you can always open the resource in the slave interpreter (iputs) instead. If this is not possible you can share the resource between the interpreters.
 % interp share {} $f iputs
 % interp eval iputs [list puts $f test]

When sharing the resource between two interpreters, remember to close the resource in both interpreters.

For an explanation of the commands, see interp

Jeez, it's unbelievable the lengths some people will go to just to avoid learning how to use namespaces.

MJ - Of course the original embedder shouldn't have overridden the command in the first place (namespaces indeed) unfortunately in an embedded or extension setting you might not be able to influence this. The whole exercise above is intended to retrieve access to the original core commands in that case.