Tcl - Append or Modify a nested list in called function

350 Views Asked by At

I have a nested list in the parent function and I want to append a few more elements to it inside one of the called functions

proc myparent {
  set mylist {}
  foreach elem $listelements {
     lappend mylist $elem
  }
 
  #at this point, mylist looks something like this:
  # {  {var1 val1} {var2 val2} {var3 val3} }

  myproc1 mylist    #--> want to append mylist here
  
  #myproc1 is expected to add another sublist to mylist. mylist after myproc1 should look like this:
  #  { {var1 val1} {var2 val2} {var3 val3} {abc def} }

  myproc2 $mylist   #--> need to use the updated mylist here
}

In myproc1 I want to append some elements to mylist. I tried the following:

   myproc1 { {list_var -list} } {
       upvar $list_var list_local
       #some conditional logic
       lappend list_local [list "abc" "def"]
   }

  

But it is not working as expected. Is upvar the right construct to be used for this requirement?

1

There are 1 best solutions below

6
Donal Fellows On

The correct way to add items to that list stored in the caller is:

proc myproc1 {list_var} {
    upvar 1 $list_var list_local

    if {[$I want to add something]} {
        lappend list_local $one_element $another_element
        lappend list_local $a_third_element
    }
}

You're recommended to always put the level count in (use 1 in this case) because it enables efficient code generation on at least some versions. It's also clearer. Once you have done the upvar, the variable effectively exists in both places at the same time.

If you lappend a list, you are making a sublist; each argument (after the variable name) to lappend becomes an element of its own.