What's the best way in Tcl v8.4 for proc to return an array?
If I have a proc that needs to return an array to its caller, what's the best way to do it?
The following code does not work in Tcl due to the impossibility of the $ array variable:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
$foo
}
tcl> set foo [mine]
Error: can't read "foo": variable is array
Alternatively, this also doesn't work:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> set foo [mine]
tcl> puts $foo(blue)
Error: can't read "foo(blue)": variable isn't array
This leaves me probably ineffective:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> array set foo [mine]
2
Or obscure:
proc mine {varName} {
upvar $varName localVar
array set localVar { red 1 blue 2 green 3 }
}
tcl>unset foo
tcl>mine foo
tcl>puts $foo(blue)
2
Is there a better way to do this, or if not, which is the most efficient?
source to share
I think you answered your own question. Simply put, you cannot return an array. There are options that you explained in your question:
1) you can return the value of the array and convert it back to an array in the caller 2) you can use upvar in your procedure to have the caller pass in the name of the array, which you can then change.
If you are using tcl 8.5 you may need to switch to using dict. Dicts are first class objects that can be passed, returned from procedures, etc.
source to share
My preference if you need to use arrays is the [get / set array] you showed:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> array set foo [mine]
2
If you are using Tcl 8.5 or later, you might consider using dicts. They will generally be faster and cleaner.
source to share