Program Structure

Tcl only has two levels of program structure: procedures and scripts.

Procedures

Procedures are declared like this: proc procName argList code All this actually does is add an entry to the table in the interpreter.

As an example: proc incr {number increment} { return [expr $number + $increment] }

Now, you can do something like this: puts [incr 10 1] and get output like this: 11

Default Parameters

The ArgList is actually a list of two-element lists, the the second element being a default value if the argument isn't supplied.

We can make use of this for incr: proc incr {number {increment 1}} { return [expr $number + $increment] } so that increment defaults to one.

Now, we can call incr with only the number argument: puts [incr 10] and get the same output: 11

Arbitrary Number of Parameters

If the last argument in the argList is named arg, then the procedure can be called with an arbitrary number of arguments (for the last argument).

As an example, a procedure that runs an operator over all of its arguments: proc fold {identity operator args} { set folded $identity foreach number $args { set folded [expr $folded $operator $number] } return $folded } and do stuff like: puts [fold 0 + 1 2 5] puts [fold 1 * 1 2 5] and get this output: 8 10

The source Command

To source a library of Tcl scripts into the current script: source fileName

Autoloading

Another way to source library scripts (that reminds me of Turbo Pascal's overlays) is autoloading. Using this mechanism, you don't source the library files, the interpreter does if for you. One advantage of this is that the libraries only get sourced if they need to be, which means memory use is as low as possible and speed may be increased if your application has lots of features that won't be used on every invocation.

To use the autoloading feature, an index file of all the library functions and which files they belong to is created. Whenever the interpreter fails to find a proc that has been called, it looks up this index and sources the associated file for you.


Previous Contents Next
Clinton Roy