Version 2 of Arrays of function pointers

Updated 2002-11-15 10:04:05

Richard Suchenwirth 2002-11-15 - I still remember how Cameron Laird groaned at me when I showed how to simulate arrays of function pointers (Tcl's equivalent being the names of functions, everything is a string). After re-reading man Tcl last night (always recommended, even after years in the business ;-), it dawned on me this morning that we don't have to simulate that - using Tcl's substitution rules, we just have it. Consider:

 #--------------------------------- dummy procs as playing material
 proc eat    x {puts "eating $x"}
 proc drink  x {puts "drinking $x"}
 proc inhale x {puts "inhaling $x"}

 #---------------------------------- building the mapping table
 array set fp {
     liquid  drink
     solid   eat
     gaseous inhale
 }
 #---------------------------------- testing:
 foreach {state matter} {solid bread  liquid wine  gaseous perfume} {
     $fp($state) $matter
 }
 #------------------- results in:
 eating bread
 drinking wine
 inhaling perfume

What happens to $fp($state)? First $state is substituted, as is the rule with arrays. Then the array element e.g. $fp(solid) is looked up in the array, and its result makes the command name eat, which finally is executed with the argument e.g. bread.


Arts and crafts of Tcl-Tk programming