why does this happen?

greenspun.com : LUSENET : Tool Command Language (Tcl) : One Thread

I am trying to understand the following sample from tcltutor. I changed the 5 in the second line from 5 to 1 to 0.0001 and the output from the interpreter remained the same. What is happening?

-------------------------------------------------------- code -------------------------------------------------------- set x 0; while "$x < 5" { set x [expr $x + 1] if {$x >6} break; if "$x > 3" continue; puts "x is $x"; } puts "exited second loop with X equal to $x\n"

----------------------------------------------- output ----------------------------------------------- x is 1 x is 2 x is 3 exited second loop with X equal to 7

-- Pngngn (tpangan@hotmail.com), February 02, 2001

Answers

That one is easy. In Tcl, tcl reads the command and its argument, makes a substitution and then calls the command.

When Tcl reads your program, here's what it does:

set x 0; while "$x < 5"

>> At this point, Tcl substitutes 0 for x , and then calls while. While only sees "0 < 5" as its argument and so when it does the expression evaluation compares 0 and 5 for ever! If you want it to do an evaluation of the variable each time, you need to code it as while {$x < 5}; that way, Tcl doesn't do that early replacement.

{ set x [expr $x + 1]

>>>Tcl increments x

if {$x >6} break; >>>The newly incremented value is compared here 1, 2, ... 7

if "$x > 3" continue;

>>>Guess what! Just as with the while, Tcl substitutes 1 for $x the first time and uses that forever more. I'm a bit fuzzy why it doesn't reevaluate it each time - probably for similar reasons.

puts "x is $x"; }

puts "exited second loop with X equal to $x\n"

-- Larry W. Virden (lvirden@cas.org), February 02, 2001.


Hi,

Thanks Larry:):)

--------------Your Reply----------------------------------------- That one is easy. In Tcl, tcl reads the command and its argument, makes a substitution and then calls the command.When Tcl reads your program, here's what it does:

set x 0; while "$x < 5"

>> At this point, Tcl substitutes 0 for x , and then calls while. While only sees "0 < 5" as its argument and so when it does the expression evaluation compares 0 and 5 for ever! <------Why?

--------------------My query------------------------------------ Why does the expression evaluation see "0 < 5" for the second evauation on when the value of x has already been changed?

Is that because in this case a substitution is being made before invocation of the while command. And one of the rules of the grouping and substitution mechanism of a tcl interpreter is that the result of a substitution is not interpreted a second time? Meaning that when the interpreter sees the word while followed by quotes, the evaluation result is taken to be the result of the first evaluation regardless of what the current value of x is?

Am I right or am I not right?

-- Pngngn Tn (tpangan@hotmail.com), February 02, 2001.


Moderation questions? read the FAQ