Version 0 of Emulating closures in Tcl

Updated 2002-01-29 07:30:20

Some languages (like Lisp family, Smalltalk, Lua) contains an interesting feature called closures. Closure represents a block of code with surrounding context, whose execution is deferred. A block can be executed later (probably more then once) with old context and newly passed arguments.

Closures often used to provide customized behaviour for some algorithm.

Tcl has no direct support for closures, but they can emulated using eval mechanism, in particular, commmands uplevel and upvar.

First example. The following command accept a block of code and executes it in specified file catalog.

 proc temp-chdir {dir block} {
         set cd [pwd]
         cd $dir
         uplevel $block
         cd $cd
 }

 # sample usage:
 temp-chdir / {puts "I'm in [pwd]"}

With upvar and uplevel it is simple to write custom iterators over some structure, like this:

 proc foreach-pocket {pw block} {
         upvar 1 $pw pwvar
         foreach p [get-container-pockets] {
                 set pwvar $p
                 uplevel 1 $block
         }
 }

 # sample usage
 foreach-pocket p {
  puts "Processing $p"
 }

mfi