Sujet : Re: Array get element with default (no error if not exist)
De : rich (at) *nospam* example.invalid (Rich)
Groupes : comp.lang.tclDate : 17. Aug 2024, 17:17:23
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v9qiej$1vbpg$1@dont-email.me>
References : 1 2 3
User-Agent : tin/2.6.1-20211226 ("Convalmore") (Linux/5.15.139 (x86_64))
RodionGork <
rodiongork@github.com> wrote:
Friends, thanks for all the replies!
And for suggestions providing insight on techniques of which I wasn't
aware of, especially that "read trace".
Yep, I definitely meant something like [array element_exists ...] rather
than [array exists ...] which seems a bit inconsistent with [dict exists
..] but of course it is not a big issue.
My curiosity was mostly satisfied, thanks! The only small thing I still
haven't grasped well is why it happened that checking for element in
array found its way into [info exists...] rather than some [array ...]
subcommands. I suspected there was something hindering implementing it
there, but probably it just, well, so happened historically :)
[info exists] is used for determining if a variable exists.
A Tcl array is built such that it is a collection of individual
variables referenced together as a set (this is also the reason why you
can't "pass" an array to a proc, nor [return] an array from a proc in
the same way you can pass/return a dict [1]).
Given that the array is merely a set of individual variables, someone,
way back in the distant past, decided it was more consistent to use the
"does this variable exist" command to determine if an individual
variable existed in an array.
[1] You can pass in the name of the array, and use upvar to access it, or
you can convert to a string and pass in the string. And to [return]
you have to convert to a string ([array get]) to return one. But this
does not work:
proc handle {arr} {
puts "I have array [array get arr]"
}
set array(1) something
handle $array
You get "can't read "array": variable is array" as an error message.
This difference is also why you can [trace] individual array elements
(they are individual variables) but cannot [trace] individual dict
elements (they are just entries inside the dict variable).