Learning the existence of commands and variables - info exists

Tcl provides a number of commands for introspection - commands that tell what is going on in your program, what the implementation is of your procedures, which variables have been set and so on.
  • The info command allows a Tcl program to obtain information from the Tcl interpreter.

The info subcommands 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.
  • info exists tests whether a variable exists and is defined.

Examples:
info exists a
# -> 0
set a 1
# -> 1
info exists a
# -> 1
info exists b
# -> 0
set b(2) 2
# -> 2
info exists b
# -> 1
info exists b(1)
# -> 0
info exists b(2)
# -> 1
info exists $a
# -> 0

That last command is an example of a common mistake: using $varname instead of just varname. Since the value of $a is 1, the command is asking if a variable named 1 exists.
It can be useful to store the name of a variable in another variable:
foreach var {a b c} {
    if {[info exists $var]} {
        puts "$var does indeed exist"
    } else {
        puts "$var sadly does not exist"
    }
}



Another thing to keep in mind is that linking variable with upvar can do funny things with the existence of variables.
 
% set a 1
1
% upvar #0 a b
% info exists b
1
% unset a
% info exists b
0
% set a 1
1
% info exists b
1


Another Example :

proc safeIncr {counter {count 1}} {
    upvar $counter c
    if { [info exists c] } {
        incr c $count
    }  else {
        set c $count
    }
}

No comments:

Post a Comment