Version 6 of info exists

Updated 2003-12-15 08:28:17

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.


See also:


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 varible 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.


Category Command - Tcl syntax help