Version 0 of Type checking

Updated 2002-11-15 15:58:02

Richard Suchenwirth 2002-11-15 - Tcl is mostly very relaxed about types (everything is a string), while other languages can spend much labor just on such classifications. Only where needed do value types matter - e.g. list functions don't accept any arbitrary string, incr wants a variable with integer value, etc.

However, if you wish you can introduce type declarations that restrict the values being assigned to a variable, via write traces. They just do a harmless operation that would raise an error if the argument is not of specified type. As Tcl's error messages are so so clear mostly, I don't bother to catch them and raise my own instead, which makes these code snippets very simple:

 proc integer args {
     foreach arg $args {
        uplevel 1 "trace var $arg w {incr $arg 0 ;#}"
     }
 }
 % integer i
 % set i x
 can't set "i": expected integer but got "x"

 proc List args {
     foreach arg $args {
        uplevel 1 "trace var $arg w {llength \[set $arg\] ;#}"
     }
 }
 % List foo
 % set foo {bar "grill}
 can't set "foo": unmatched open quote in list

Category Concept | Arts and crafts of Tcl-Tk programming