Sujet : Re: Array get element with default (no error if not exist)
De : ralfixx (at) *nospam* gmx.de (Ralf Fassel)
Groupes : comp.lang.tclDate : 16. Aug 2024, 10:11:29
Autres entêtes
Message-ID : <ygao75szvb2.fsf@akutech.de>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
* RodionGork <
rodiongork@github.com>
| Is there some motivation why some command for get-with-default is not
| implemented, e.g.
>
| puts [array peek $a 2 "default value"]
Most probably because up to now nobody required it so badly that s/he
implemented it, since the [info exists] approach is not too bad IMHO.
proc array_peek {arr key default} {
upvar $arr a
if {![array exists a] || ![info exists a($key)]} {
return $default
}
return $a($key)
}
array set a {1 one}
array_peek a 1 "default value"
=> one
array_peek a 2 "default value"
=> default value
Or you could set up a read-trace on the array to provide non-existing values:
array set a {}
trace add variable a read set_array_default
proc set_array_default {name1 name2 op} {
upvar a $name1
# puts stderr "set_array {$name1} {$name2} {$op}"
if {![info exists a($name2)]} {
set a($name2) "default"
}
}
set a(2)
=> default
Though that would alter the array and make the key exists which might
not be what you want.
HTH
R'