The source
command always evaluates the file's contents at the current level; it really is effectively just read the file's contents into a string and then eval
that (except for a little trickery with info script
). That means that if you want to source
a file in the global context, you should do one of these:
# Quotes around #0 just because of Stack Overflow's highlighting
uplevel "#0" {
source thefile.tcl
}
uplevel "#0" [list source $thefile]
namespace eval :: {
source thefile.tcl
}
namespace eval :: [list source $thefile]
The versions with list
are doing code generation, and will work much better when the filename is in a variable (or generated by a command like file join
); if everything is literal, you're better off using the braced versions.
The versions with uplevel #0
are different from the versions with namespace eval ::
in that the former goes up the stack to the global level, whereas the latter just pushes a new stack frame that you can uplevel
out of. Most of the time, with sane code, the differences are very slight; use the one you prefer as both are good code.