Forum OpenACS Q&A: nice little tcl gotcha

Collapse
Posted by Jonathan Ellis on
I'm a brace minimalist; I don't like to brace things where they're not required to make sense to tcl. So today I wrote a loop like this:
set p 1
while $p {
    set p 0
}
it took me a while to figure out that the reason this never terminates is you NEED to brace the loop test or it only gets evaluated once.
Collapse
Posted by David Walker on
funny. I'm the opposite. I like to throw in lots of braces.

You can also do neat stuff like this. The variable bracetest gets evaluated once but the $p that is the contents of that variable gets evaluated for each iteration.
set bracetest "$p"
set p 1
while $bracetest {
	set p 0
}
Collapse
Posted by Lars Pind on
Uhm, David, don't you want to say set bracetest {$p}, so you don't get a p not defined error?

And Jonathan, what's the point of being a brace minimalist? Does it add any performance?

I'm all for braces. They make the code more legible. I always add them to code that doens't.

We should include something about braces in the standards doc.

Collapse
Posted by David Walker on
You're right Lars. I got bit by the backslash bug.

My post was supposed to say
set bracetest "$p"
Collapse
Posted by Titi Ala'ilima on
I tend to over-brace, myself. (I greatly prefer bracing SQL rather than quoting it when there is no need for evaluation.)

Anyway, this is a wonderful example for teaching Tcl newbies how the interpreter works. Understanding when things are evaluated is of vital importance.

Speaking of which, one annoying pseudo-Tcl construct is the db_foreach. I'm sure some of you have encountered the problem with trying to return from within something like this, as it's actually evaluating in a different context. I've found you can use a "return -code return", but I also found that this doesn't work inside the if_no_rows clause. I haven't taken the time to look too deeply into it, but my guess is it evaluates that bit two contexts down, so the "return -code return" only exits out of two contexts but not the context in which it looks like you're calling it.

Collapse
Posted by Lars Pind on
When do you need to return from withing a db_foreach? I can't remember ever having had to do that.