1. Util Macros
The Util macros are a collection of frequently
used code. These all start with a star character *.
Following are some of the more commonly used ones.
1.1 *catch
Eval with catch, displaying any errors as a warning.
The warning message also contains the namespace (and proc if possible)
of the offending call.
When not running with wize -Wall, errors are silently ignored.
*catch { CallFunc 1 "X" }
# Equivalent to ...
if {[catch { CallFunc 1 "X" } erc]} {
.Warn "Catch: $erc"
}
1.2 *value
Returns the value of a variable if it exists, otherwise returns the default,
or if no default is given, an empty string, eg.
set n [*value ::MyNs::Arr(Really_Long_Value) 0]
# Equivalent to ...
if {[info exists ::MyNs::Arr(Really_Long_Value)]} {
set n $::MyNs::Arr(Really_Long_Value)
} else {
set n 0
}
1.3 *bvalue
Return the value for an element from a binary (name/value pair) list. If available,
the dict command is used, otherwise falls back to a list search.
set LookupTable {able 1 baker 2 charlie 3}
set val [*bvalue $LookupTable baker 0]
# Equivalent to ...
if {[dict exists $LookupTable baker]} {
set val [dict get $LookupTable baker]
} else {
set val 0
}
1.4 *fread/*fwrite
Read or write a file. Additional options are passed to fconfigure:
set dat [*fread file1.dat]
*fwrite file2.dat $dat -translation binary
# Equivalent to ...
set fp [open file1.dat]
set dat [read $fp]
close $fp
set fp [open file2.dat w+]
fconfigure $fp -translation binary
if {[catch { puts -nonewline $fp $dat } erc]} {
close $fp
error $erc
}
close $fp
© 2008 Peter MacDonald