Search code examples
tclproc-objectupvar

Unable to pass a variable to a procedure using upvar in Tcl


I need a procedure that will be able to access, read and change a variable from the namespace of the caller. The variable is called _current_selection. I have tried to do it using upvar in several different ways, but nothing worked. (I've written small test proc just to test the upvar mechanism). Here are my attempts:


call to proc:

select_shape $this _current_selection

proc:

proc select_shape {main_gui var_name} {
    upvar  $var_name curr_sel
    puts " previously changed:  $curr_sel"
    set curr_sel [$curr_sel + 1]
}

For my second attempt:

call to proc:

select_shape $this

proc:

proc select_shape {main_gui} {
    upvar  _current_selection curr_sel
    puts " previously changed:  $curr_sel"
    set curr_sel [$curr_sel + 1]
}

In all the attempts, once it reaches this area in the code it says can't read "curr_sel": no such variable

What am I doing wrong?

EDIT:

The call for the function is made from a bind command:

$this/zinc bind current <Button-1> [list select_shape $this _current_selection]

at start I thought that it doesn't matter. but maybe It does.


Solution

  • I believe that bind commands operate in the global namespace, so that's where the variable is expected to be found. This might work:

    $this/zinc bind current <Button-1> \
        [list select_shape $this [namespace current]::_current_selection]