A common way of structuring related commands is to group them
together into a single command with sub-commands. This type of
command is called an ensemble command, and there are many
examples in the Tcl standard library. For instance, the
string command is an ensemble whose
sub-commands are length, index,
match etc. Tcl 8.5 introduced a handy way of
converting a namespace into an ensemble with the namespace
ensemble command. This command is very flexible, with many
options to specify exactly how sub-commands are mapped to commands
within the namespace. The most basic usage is very straightforward,
however, and simply creates an ensemble command with the same name
as the namespace and with all exported procedures registered as
sub-commands. To illustrate this, we will convert our stack data
structure into an ensemble:
package require tutstack 1.0
package require Tcl 8.5
namespace eval ::tutstack {
# Create the ensemble command
namespace ensemble create
}
# Now we can use our stack through the ensemble command
set stack [tutstack create]
foreach num {1 2 3 4 5} { tutstack push $stack $num }
while { ![tutstack empty $stack] } {
puts "[tutstack pop $stack]"
}
tutstack destroy $stack
As well as providing a nicer syntax for accessing functionality in a namespace, ensemble commands also help to clearly distinguish the public interface of a package from the private implementation details, as only exported commands will be registered as sub-commands and the ensemble will enforce this distinction. Readers who are familiar with object-oriented programming (OOP) will realise that the namespace and ensemble mechanisms provide many of the same encapsulation advantages. Indeed, many OO extensions for Tcl build on top of the powerful namespace mechanism.