Updated 2013-10-09 14:28:01 by s
info exists varName

Returns 1 if the variable named varName exists in the current context (either as a global or local variable) and has been defined by being given a value, returns 0 otherwise.

Called with a variable or array element name (no $ in front!), returns 1 if the variable or array element exists, else 0.
  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

Notice the last one - if the user thought they were testing to see if the a variable exists, they used the wrong syntax - saying $a means read the contents of the a variable, and see if there is a variable by that name.

-- It doesn't have to be wrong syntax, actually: it's often useful to have one variable reference others, like this:
  foreach var {a b c} {
      if {[info exists $var]} {
          puts "$var does indeed exist"
      } else {
          puts "$var sadly does not exist"
      }
  }

Then again -
  set a b
 b
  info exists $a
 1

Unintentionally setting a to a value that equals the name of an existing variable yields a false positive when erroneously (in this case) checking the value of a.

huck. Shouldn't this be 0, since variable b 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.
 % 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

2003-12-21 VI I remember reading that info exists is slow on some versions of Tcl on large arrays. Anybody have more info on that?

2007-12-29 DKF: From 8.5 onwards, info exists is byte-compiled.


See also edit