Updated 2013-03-05 02:24:55 by pooryorick

Summary  edit

Richard Suchenwirth 2002-11-15: I still remember how Cameron Laird groaned 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.

Description  edit

#--------------------------------- 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 {solid eat liquid drink 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.

KPV 2002-11-15: funny, I use an array of function pointers in the Møiré Patterns program I posted here just yesterday. I needed to draw the foreground or background as one of several patterns and I wanted an easy way to make this extensible. So I just created an array of function pointers, and now to add a new type is just write the subroutine and add its name and reference to the array. Furthermore, in the GUI widget where the user can select the type, I just use [array names fptr] to get the list. Below is the relevant code snippets:
array set fptr {"Parallel Lines" Parallel "Radial Lines" Radial \
    Circles Circles}

proc Show {who angle} {
    global fptr SS
    $fptr($SS($who,type)) $who $angle