identical123456
identical123456

Reputation: 321

How to reference a variable within a proc in another proc

I have a proc that evaluates an expr and appends to a particular list locally

proc a {} {
set mylist ""
set out [expr...
lappend mylist $out
}

I want to use the "mylist" list outside of the "a" proc without declaring it as global or without returning that list from within the proc using "return mylist". How do I go about doing that. I have two use cases, Use the variable within another proc:

proc b {} {
do something with the "mylist" from proc a
}

Use case 2 :

Just use it outside the proc [Not within another proc]

Upvotes: 1

Views: 2024

Answers (2)

Sharad
Sharad

Reputation: 10622

Reference: https://www.tcl-lang.org/man/tcl/TclCmd/upvar.htm

Sample code snippet:

proc foo {ref_var} {
  upvar $ref_var local_var
  # do some operatins
  lappend local_var 20
}

proc bar {} {
  set a [list 10]
  puts "Before: $a"
  foo a
  puts "After: $a"
}

# nested proc
bar

# without proc
set c [list 30]
puts "Initial: $c"
foo c
puts "Final: $c"

Output:

Before: 10
After: 10 20
Initial: 30
Final: 30 20

Upvotes: 0

Schelte Bron
Schelte Bron

Reputation: 4813

The "mylist" variable only exists as long as proc a is being executed. Whenever a proc finishes, all its local variables are cleaned up.

As long as a is in progress, you can access its variables using the upvar command.

For example: if you call b from a, b can access "mylist" using:

upvar 1 mylist othervar
puts $othervar

However, it is usually better practice to pass the variable (or at least its name) between procs, or make it a global or namespace variable.

Upvotes: 4

Related Questions