Welcome, guest | Sign In | My Account | Store | Cart

A straightforward routine to allow easy creation of new methods based on a previous template. The implementation language is XOTcl. This could also be considered a showcase for some XOTcl features.

Tcl, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Based on code at http://mini.net/cgi-bin/wikit/401.html

package require XOTcl  ;# http://www.xotcl.org/


# We dynamically install this method for the "Class" meta-class. This
# means all classes will be provided with this method. One could
# also create a separate meta-class to do this and create classes from it
# instead.

@ Class instproc instFromTemplate {
    procName {Name of instproc to create.}
    object {Object containing template proc}
    template {Name of proc to use as template.}
    subList {
        Key-value substitution list where the key is a regexp and the value
        is a subSpec as in [regsub].
    }
} {
    description {
        Creates an instproc from a template proc by copying the template and
        replacing specified data. Extremely useful for meta-programming. 
    }
}

Class instproc instFromTemplate {procName object template subList} {
    set body [$object info body $template]
    foreach {regexp subSpec} $subList {
        regsub -all -- $regexp $body $subSpec body
    }
    [self] instproc $procName [$object info args $template] $body
}

Meta-programming can be extremely useful for certain large-scale structural problems. I used it myself for work with the ENIÄK library being developed (http://dev.fishpool.fi/oss/eniak/) as an attribute method generator. For many object classes I had a bunch of very similar methods which were really doing the same thing with slightly different data. I changed that, so now I use an "attributes" method when creating a class. This automatically creates methods to handle those attributes, and keeps the code short and clean.

Created by Kristoffer Lawson on Sat, 8 Sep 2001 (MIT)
Tcl recipes (162)
Kristoffer Lawson's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks