Previous section   Next section

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

Table of Contents
Chapter 14.  Namespaces

Converting Existing Packages to use Namespaces

Suppose you have an existing set of Tcl procedures that you want to wrap in a namespace. Obviously, you start by surrounding your existing code in a namespace eval block. However, you need to consider three things: global variables, exported procedures, and callbacks.

  • Global variables remain global until you change your code to use variable instead of global. Some variables may make sense to leave at the global scope. Remember that the variables that Tcl defines are global, including env, tcl_platform, and the others listed in Table 2-2 on page 30. If you use the upvar #0 trick described on page 86, you can adapt this to namespaces by doing this instead:

    upvar #0 [namespace current]::$instance state
  • Exporting procedures makes it more convenient for users of your package. It is not strictly necessary because they can always use qualified names to reference your procedures. An export list is a good hint about which procedures are expected to be used by other packages. Remember that the export list determines what procedures are visible in the index created by pkg_mkIndex.

  • Callbacks execute at the global scope. If you use variable traces and variables associated with Tk widgets, these are also treated as global variables. If you want a callback to invoke a namespace procedure, or if you give out the name of a namespace variable, then you must construct fully qualified variable and procedure names. You can hardwire the current namespace:

    button .foo -command ::myname::callback \
        -textvariable ::myname::textvar

    or you can use namespace current:

    button .foo -command [namespace current]::callback \
        -textvariable [namespace current]::textvar

      Previous section   Next section