Wiki: Tcl

Use incr to avoid initialisation

Incrementing an undefined variable will act like the variable was a zero. So an initial set x 1 can be replaced with incr x, or an initial set x 0 can be removed entirely. Same with similar functions like append and lappend.

Looping

time can be used to repeat a block n times. while loops until a condition is true, if the condition is simple enough, you can escape it rather than use {} to save a byte. for loops are always longer than whiles. foreachs can be replaced with lmaps.

set n 5;while \$n {incr x $n;incr n -1}
set n 5;time {incr x $n;incr n -1} $n

Nest statements

[]s can be used to recursively evaluate an expression, returning the value. So try to nest those incrs and sets when you can.

incr x
time {set x [expr $x*[incr n]]} 5

Use numeric variables as variable variables

You can use anything as a variable name, even numbers, which can then be sourced from other variables. This are called variable variables in other languages like PHP, and can mostly be used as a source of unique uninitialised variables in loops.

# Generates squares
time {time {incr $x $x} [incr x];eval puts\ $$x} 9

Construct expressions without evaluating them

You can assign mathematical expressions as strings to variables without evaluating them, to be evaluated later explicitly or as a condition for if and while statements. If you know the structure of the expression, you can even manipulate them with higher precedence operators.

set x 2+3
puts [expr $x*0]
puts [expr 0*$x]