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
- Each proc that uses a namespace variable has a
variableline for it. - A package keeps its commands in one namespace, and exports only the commands for its users.
- A name with
::at the start is a full name. Look for a short name that can find a command of the same name at the top level. namespace evalruns its body in the namespace. In ztcl, as in Tcl 8.6,set x 1in that body changes the globalxwhen one exists. A namespace variable gets its first value withvariable x 1.
Ask an agent
Put the procs of
jotin the namespacejot, with onevariableline for each namespace variable in each proc, and an ensemble withnamespace ensemble create. Export onlyadd,show, andcount.
Try this
- Fix
jot::clearwith avariableline, and run it again. - Add
clearto the ensemble withnamespace eval jot { namespace export clear }, and runjot clear. - Run
namespace children ::.