As far as I understand, in tcl if you want to pass a named array to a function, you have to access the upper scope of the caller via the upvar
command within the callee body. Is this the only way to pass an array in tcl ?
3 Answers
As Michael indicated, there are several ways, plus a wiki page that discusses it. Just to have some of that information here, some options are:
By Upvar
proc by_upvar {&arrName} {
upvar 1 ${&arrName} arr
puts arr(mykey)
set arr(myotherkey) 2
}
set myarr(mykey) 1
by_upvar myarr
info exists myarr(myotherkey) => true
- results in changes to the array being seen by the caller
By array get/set
proc by_getset {agv} {
array set arr $agv
puts arr(mykey)
set arr(myotherkey) 2
return [array get arr]
}
set myarr(mykey) 1
array set mynewarr [by_upvar myarr]
info exists myarr(myotherkey) => false
info exists mynewarr(myotherkey) => true
- results in changes to the array being seen by the caller
- similar mechanism can be used to return an array
-
What's up with the amperand in your by_upvar proc? Not Tcl syntax. Aug 20, 2010 at 20:17
-
@glenn jackman: "not tcl syntax"? Nonsense! Everything is tcl syntax :-). Since variable names can be any string and & is used in some other languages to signify the address of a variable, it makes a handy semi-quasi-self-documenting way of desgnating it as a target of an upvar. Funny how after all oh-so-many years I never thought to use &; I usually use _ or fooVar (upvar $fooVar foo). Aug 21, 2010 at 2:13
-
OK, true. I usually use "varname". There is an error in the upvar command though: should be
upvar 1 $&arrName arr
Aug 21, 2010 at 10:41 -
Updated to account for the error (&a -> ${&a}). As Bryan, indicated, it's used merely as a self-documenting way of saying it's an upvar'd variable name. I can't take credit for it though, as I copied it from some other well known Tcler, though I can't recall from who.– RHSeegerAug 23, 2010 at 0:20
There are other ways, like converting it into a list first (via array get
and array set
).
If you're only passing in the value of the array, you could pass in a dictionary instead (hint: array get
serializes an array into a dictionary value) and use the dict
command to access values in it. But if you want access to the live value, upvar
is definitely easiest. It's also a very fast technique; it compiles down to an extra traversal of a pointer during variable access after upvar
itself finishes.