Skip to content

TCL

File information

Source

foreach

Source

# Usage
foreach varname list body
# Basic
foreach var {1 2 3 4} {
    puts $var
}
# The value of x is "b a d c f e"
# There are 3 iterations of the loop.
set x {}
foreach {i j} {a b c d e f} {
    lappend x $j $i
}
# The value of x is "a d b e c f {} g"
# There are 4 iterations of the loop.
set x {}
foreach i {a b c} j {d e f g} {
    lappend x $i $j
}
# The value of x is "a d e b f g c {} {}"
# There are 3 iterations of the loop.
set x {}
foreach i {a b c} {j k} {d e f g} {
    lappend x $i $j $k
}

Get directory of current script

set script_dir [file dirname [ file normalize [ info script ] ] ]

Note

This will be the directory of the script that this line is written in.

Sourced files will still report the directory that the file that was sourced is in.

Maths in variable assignment (using expr)

Source

This is not correct:

$ set a 1
$ set b 2
$ set c [$a + $b]
> invalid command name "3"

This is correct:

$ set a 1
$ set b 2
$ set c [expr $a + $b]

Return

Source

The return statement in tcl has various optional arguments:

return ?-code code? ?-errorinfo info? ?-errorcode errorcode? ?value?

These allow the return to directly trigger an error.

Example:

return -code error -errorinfo "Return Generates This" -errorcode "-999"