Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing arrays to functions in tcl. Only upvar?

Tags:

tcl

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 ?

like image 529
Stefano Borini Avatar asked Aug 18 '10 14:08

Stefano Borini


People also ask

How do you pass an array to a function in Tcl?

If you want to pass an array, which s essentially a collection of variables, to a procedure in TCL, you can use the command `upvar` as explained earlier. You are passing a name to the procedure and then using it to access the array at the previous level.

What does Upvar do in Tcl?

upvar , a built-in Tcl command, links a variable at the current level to another variable at or above the current level.

Can you have pass arrays to functions as arguments?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.

How do you declare an array in Tcl?

Creating an Array To create multiple array keys and values in one operation, use array set. Array names have the same restrictions as any other Tcl variable. In Tcl, everything is a string. Quoting strings is mostly not necessary, and can even be a problem, as in the previous example.


2 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
like image 176
RHSeeger Avatar answered Oct 02 '22 16:10

RHSeeger


There are other ways, like converting it into a list first (via array get and array set).

like image 20
Michael Avatar answered Oct 02 '22 18:10

Michael