Namespaces

A namespace is a group of commands and variables with a name, such as jot. It keeps the names of a package apart from the names of other code. An ensemble makes the procs of a namespace into the subcommands of one command. This lesson makes jot add and jot show.

The jot namespace

namespace eval jot {
    variable notes {}
    proc add {text} {
        variable notes
        lappend notes [dict create text $text done 0]
        return [llength $notes]
    }
    proc show {} {
        variable notes
        set i 0
        foreach n $notes { puts "[incr i]. [dict get $n text]" }
    }
    proc count {} { variable notes; llength $notes }
    namespace export add show count
    namespace ensemble create
}

Now jot is one command: jot add "buy milk", jot add "fix the bike", and jot show. The full name of a proc works too: jot::count. A wrong subcommand gives the list of the right ones: jot list.

Names in a namespace

variable notes in a proc links the name to the variable of the namespace, as global does for the top level. Code outside reads it with the full name: set jot::notes. info commands jot::* lists the procs.

A name that starts with :: is a full name from the top. A name with no :: is looked up in the current namespace, then at the top level for a command. namespace export lists the procs of the ensemble, and the other procs stay inside.

A proc that forgets variable

A proc in a namespace that sets notes with no variable line makes a local variable. The proc runs with no error, and the notes do not change. namespace eval jot { proc clear {} { set notes {} } } makes that bug. jot::clear runs, and jot::count shows that the notes are still there.

Reading code an agent wrote

Ask an agent

Put the procs of jot in the namespace jot, with one variable line for each namespace variable in each proc, and an ensemble with namespace ensemble create. Export only add, show, and count.

Try this