Re: Use "range," not "for"?

From: Bryan Oakley (bryan_at_bitmover.com)
Date: 02/13/04


Date: Fri, 13 Feb 2004 01:20:00 GMT

David McClamrock wrote:
> Thanks to everyone who suggested ways to get a proc to recognize all
> variables in the global scope--here's why I wanted to know. (Maybe someone
> has done this better already--if so, don't hesitate to let me know!)
>
> I've found that a simple "foreach" loop fairly often won't do the jobs I
> want done, and I need to use "for"--ugh! Well, I recently read at least
> part of a book about Python. It didn't look like an improvement over Tcl
> for the most part, but it has at least a few good features, one of which is
> the "range" expression. I thought a "range" procedure in Tcl might be a
> good substitute for the clumsy "for." So, here's my first effort. Instead
> of writing this:
>
> for {set i 1} {$i<= 10} {incr i} {puts "$i. \"for\" is ugly!"}
>
> you can write this:
>
> range i 1 to 10 {puts "$i. \"range\" is beautiful!"}

Using globals is not the right solution. Your range code simply won't
work inside a procedure. Try running this code:

proc foo {} {
     set j "Hello, world"
     range i 1 to 10 {
         puts "$i: $j"
     }
}

You'll instantly see the problem. Instead of using global variables you
need to use upvar and "uplevel 1".

Also, the very first uplevel "uplevel #0 proc ..." really doesn't do
anything. What do you think it does? If you can explain what you are
trying to accomplish we can tell you a better way to accomplish it. If
you're trying to force the definition of range into the global scope
it's better to fully qualify the name, ie: "proc ::range".



Relevant Pages

  • Re: save and restore globals
    ... # the problematical variables manually - one time I received during restore ... # set lsg [info globals] ... # puts "saves:$saves" ... All of this is taking place with a proc, ...
    (comp.lang.tcl)
  • Re: TCL equivalent of PHP "phpinfo()"?
    ... The problem is that you are trying to access globals without declaring ... # output: "foobar doesn't exist" ... proc a { ...
    (comp.lang.tcl)
  • Re: defining a constant or define ?
    ... > defining it as global FLAG_1 first. ... Declaring globals that enter the local scope allows you to work locally, ... Why don't you just run your Tcl program through cpp? ... Let's support this style by overloading the proc command. ...
    (comp.lang.tcl)
  • Re: TCL equivalent of PHP "phpinfo()"?
    ... It's a great proc, Roy, but I have no clue as to how to use it ... globals LIST TO EXIST WITHIN PROC CONSTRUCT (TCL EQUIV OF JAVA ... I have this proc instead that works that doesn't use parray because, ... Rather Tcl has globals period. ...
    (comp.lang.tcl)
  • Re: Tcl "source" command
    ... inside the proc. ... # else define the globals explicitly ... It looks like this is trying to execute a command named "incr ...
    (comp.lang.tcl)