Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Initialize all vars or rely on info exists?

34 views
Skip to first unread message

Nomen Nescio

unread,
Mar 25, 2012, 2:48:03 PM3/25/12
to
Is it better to initialize all variables whether they might be used or not,
or better to test with info exists?

I am scanning some text and variables only get created if specific patterns
match. I found out if I test for an empty string the script gets an error. I
"solved" this by doing set for all the possibly used variables to the empty
string "". Looking a bit further I see I could use info exists. Tcl noob as
I am, I don't know whether info exists is preferable or initializing lots of
variables that may not be used is better. I don't mind the memory
consumption of creating variables that might not be used. The question is
whether there's any benefit in Tcl to defining variables that might not be
used and if that is the right way to do this in Tcl or should I use info
exists? I would prefer to do it idiomatically, with a priority on clarity
and then performance and then storage consumption in that order. Of course I
want to do it like a Tcler. Thanks guys.

Alexandre Ferrieux

unread,
Mar 25, 2012, 4:42:34 PM3/25/12
to
Info exists is indeed an elegant way of encoding the "I was there" bit
out of band, rather than in-band. There are several benefits:

- no risk of value collision (being out of band)
- code maintainability (no double enumeration of vars: init vs.
runtime)
- generality: can also be used (typically with arrays) with an
unbounded number of vars/keys

Even if you're worried by a possible performance implication, you
should not: both "if {$x}" and "if {[info exists x]}" get dedicated
bytecode instructions (loadScalar and existsScalar), and the remaining
delta is very small because "existsScalar" has a side-effect of
storing the parsedVar in the internal representation, so the hashtable
lookup penalty is paid for just once.

In short: go for [info exists] :)

-Alex
Message has been deleted
0 new messages