Variables containing variable names 
Author Message
 Variables containing variable names

Hi all,

I need to create a set of variables from a list and compare them
against some constants.

The code I'm using is

proc create_var {} {
  set args [list x y z]
  foreach item $args {
    global $item
    set $item 1
    # conscious decision to use {global $item} and not {global item}
  }

# This should create 3 global vars $x $y $z with their values as 1 1 1
create_var

# print them
puts "$x $y $z"

# However, I seem to have a problem when I'm trying to compare $x $y and $z
# with 1.

proc check_var {} {
  set args [list x y z]
  foreach item $args {
    global $item
    if {1 == $item} {
      # Obviously failing; comparing "1" against "x" "y" "z"
      puts "It works"
    }
  }

Quote:
}

Is there any mechanism that is available whereby we can access the contents
of $item as TCL variable?

Thanks,
Syd



Sat, 27 Aug 2005 23:18:28 GMT  
 Variables containing variable names

Quote:

> I need to create a set of variables from a list and compare them
> against some constants.
> The code I'm using is
<snip>
> Is there any mechanism that is available whereby we can access the contents
> of $item as TCL variable?

This is a job for [upvar].

--
| Don Porter          Mathematical and Computational Sciences Division |

| http://math.nist.gov/~DPorter/                                  NIST |
|______________________________________________________________________|



Sat, 27 Aug 2005 23:28:50 GMT  
 Variables containing variable names

Quote:

> proc check_var {} {
>   set args [list x y z]
>   foreach item $args {
>     global $item
>     if {1 == $item} {
>       # Obviously failing; comparing "1" against "x" "y" "z"

Note that [set x] and $x do the same thing, so [set $item] is your answer.

      if {1 == [set $item]} {

Quote:
>       puts "It works"
>     }
>   }
> }

--
Glenn Jackman
NCF Sysadmin



Sat, 27 Aug 2005 23:55:03 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Using a variable name for a variable name??

2. Support for Linking Tcl Variables and C Variables Containing References to Tcl_Obj Structures

3. Variable containing Field Name

4. variable contents to variable name

5. array name in variable variable

6. getting variable name from the variable itself?

7. name of a variable stored in another variable

8. Variable variable names?

9. values of variable variable-names

10. Class variables / global variables / Init variables

11. field name and key name as a variable

12. field name and key name as a variable

 

 
Powered by phpBB® Forum Software