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?
The correct way to add items to that list stored in the caller is:
You're recommended to always put the level count in (use
1in this case) because it enables efficient code generation on at least some versions. It's also clearer. Once you have done theupvar, the variable effectively exists in both places at the same time.If you
lappendalist, you are making a sublist; each argument (after the variable name) tolappendbecomes an element of its own.