'''`[info] exists`''' tests whether a [variable] exists and is defined.
** Synopsis **
: '''info exists''' ''varName''
** Description **
'''`[info] exists`''' tests whether a [variable] exists and is defined.
** Synopsis **
: '''info exists''' ''varName''
** Description **
Returns `1` if the variable named ''varName'' exists in the current context according the the rules of [namespace%|%name resolution], and has been defined by being given a value, returns `0` otherwise. To check whether a variable exists precisely in a certain namespace, fully-qualify the variable name.
`info exists` returns `0` for variables that exist but are undefined. This can
happen, for example, with `[trace]`, because if a trace is set on a nonexisting
variable, `[trace]` will create that variable, but leave it undefined.
Although `info exists` doesn't detect undefined variables, `[namespace which]
-variable` does. In that case, it's usually a good idea to pass a fully-qualified variable name to `[namespace which] -variable`.
'''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"
}
}
======
----
[KPV]: Another thing to keep in mind is that linking variable with
`[upvar]` can do funny things with the existence of variables.
======none
% 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
======
----
2015-12-01 `info exists` allows for the following typo to go on undetected for a while:
======
if {[info exists ARRAY(KEY]} { # note the missing ')' in the array variable name.
# ...
}
======
[AM] 2015-12-01 That is a consequence of the incredible freedom you have in using variable names. The above checks for a variable "ARRAY(KEY", not an element of the array ARRAY. You can set that variable and get its value like:
======
set ARRAY(KEY 1
puts ${ARRAY(KEY}
======
Note the braces around the name - otherwise you would get a syntax error as the name is not composed of just letters and digits and underscores.
----
[VI] 2003-12-21: I remember reading that `info exists` is slow on some versions
of Tcl on large arrays. Anybody have more info on that?
----
[DKF] 2007-12-29: From 8.5 onwards, '''info exists''' is byte-compiled.
** See Also **
`[info]`:
`[namespace which] -variable`:
<<categories>> Command | Tcl syntax