Table of Contents
Tcl provides a number of commands for introspection
The info command allows a Tcl
program to obtain information from the Tcl interpreter. The next
three lessons cover aspects of the info command. (Other commands allowing
introspection involve: traces, namespaces, commands scheduled for
later execution via the after command
and so on.)
This lesson covers the info
subcommands that return information about which procs, variables,
or commands are currently in existence in this instance of the
interpreter. By using these subcommands you can determine if a
variable or proc exists before you try to access it.
The code below shows how to use the info
exists command to make an incr that will never return a
no such variable
proc safeIncr {val {amount 1}} {
upvar $val v
if { [info exists v] } {
incr v $amount
} else {
set v $amount
}
}
Info commands that return lists of visible commands and variables.
Almost all these commands take a pattern that follow the
string match
rules. If pattern is not provided, a list
of all items is returned (as if the pattern was "*").
info commands ?pattern?Returns a list of the commands, both internal commands and procedures, whose names match
pattern.
info exists varNameReturns 1 if
varName exists as a
variable (or an array element) in the current context, otherwise
returns 0.
info functions ?pattern?Returns a list of the mathematical functions available via the
expr command that match
pattern.
info globals ?pattern?Returns a list of the global variables that match
pattern.
info locals ?pattern?Returns a list of the local variables that match
pattern.
info procs ?pattern?Returns a list of the Tcl procedures that match
pattern.
info vars
?pattern?Returns a list of the local and global variables that match
pattern.