0

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?

dgarg
  • 318
  • 1
  • 3
  • 13

1 Answers1

0

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.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • But `mylist` is a nested list, something like `{ {myvar1 val1} {myvar2 val2} }` and in myproc1, i want to append another element like `{abc def}`. This is why I used `lappend list_local [ list "abc" "def"]` – dgarg Jul 06 '21 at 20:40
  • @dgarg You should edit your question to include a sample list and what the appended one should look like. – Shawn Jul 06 '21 at 20:46
  • @Shawn edited the question to show sample list and expected appended list – dgarg Jul 06 '21 at 20:51
  • @dgarg Your myproc1 works for me. Adds a new element, itself a 2-element list, to the end of mylist. – Shawn Jul 06 '21 at 21:00
  • True. I tried a simple testcase and it works for me as well. But in my full program, i am getting `invalid bareword "lappend" in expression "...!= "" should be "$lappend" or "{lappend}" or "lappend(...)" or ...` – dgarg Jul 07 '21 at 09:54
  • My mistake.. somehow deleted the closing brace in the if condition before lappend. TCL is so hard to debug for silly mistakes as the errors are cryptic and no line number given. – dgarg Jul 08 '21 at 12:12