Version 2 of Variable substitution in -command scripts

Updated 2003-07-10 09:01:41

ramsan says: A typical problem when trying to define the command script is when you want to mix variables that need to be substituted now and others that need to be substituted later. Some examples:

  • If variables need to be substituted now:
        button $b -command [list $b configure -background red]
        button $b -command "[list $b configure -background red] ; [list puts \
           "pressed $b"]"
  • If variables need to be substituted later:
       button $b -command {
           set aa $some_global_var
       }
  • If there is a mixure:
       button $b -command [list some_function $b] ;# recommended solution
  • If you really want to avoid to create new functions and want an inline solution, there are some possibilities:
       button $b -command [string map [list %W $b] {
           set aa $some_global_var
           %W configure -background red
       }]

or:

      set cmd {
           set aa $some_global_var
           %W configure -background red
       }
       button $b -command [string map [list %W $b] $cmd]

it is the same but different disposition.

There are other solutions that become easily complex and error prone:

       button $b -command "
           set aa \$some_global_var
          $b configure -background red
       "

[ Category Example ]