Control Flow

Alternation

Choosing from several choices.

if Commmand

A simple example: if {10 < 3} { puts "i'm worried..." } Note that we have to use K&R style bracketing, because if we started it on the next line, the newline would end the if command, and it would only recieve one argument.

The if command has optional elseif arguments that make the next two arguments another expresion, and a block of code of that is executed if it is true: if {10 < 3} { puts "i'm worried..." } elseif {3 <= 5} { puts "three is smaller than five" } which outputs: three is smaller than five

Lastly, the if command as an else argument, which causes if to run the following code block if none of the preceding code blocks were true: if {10 < 3} { puts "i'm worried..." } elseif {3 == 5} { puts "three is equal to five" } else { puts "i give up" } which outputs: i give up

switch Command

The switch command is just another way to write if statements. There are two forms of the switch command. The following two pieces of code are equivalent:
If Switch
if {$x == expr1} { code1 } elseif {$x == expr2} { code2 } else { code3 } switch $x { expr1 code1 expr2 code2 default code3 }

An example: gets stdin key switch $key { j {puts down} k {puts up} h {puts left} l {puts right} }

Iteration

Repeating a bunch of statements.

while Command

Syntax: while expr code Keep executing code until expr is true.

for Command

Syntax: for init test reinit body

Execute init.

If test is true, run body then reinit. Repeat until test is false.

foreach Command

Iterates over a list, here is an example of how to iterate over an array: foreach x [array names function] { set function($x) [expr $function($x) * 2] }

Breaking Out

Doing things a little differently.
break

Terminates the innermost nested looping command.

continue

Terminates the current iteration of the innermost looping command and goes on the next iteration of that command.


Previous Contents Next
Clinton Roy