Richard Suchenwirth 2003-11-04 - A colleague asked me for a skeleton for simple OO in Tcl, and said I should wikify it too ;) - so here it is. It basically has only one "singleton class" filetbl, and mixes generic and specific code - I marked the specific parts, so you can put your own content there. But it's simple, and maybe interesting to read. Note also that no "OO framework" is needed at all - Tcl just can by itself, if one wishes :^)
Namespaces are created with namespace eval, before we can populate them with procs or variables:
namespace eval filetbl { variable n 0 } #---------------------------------- Constructor proc filetbl::create filename { variable n set fp [open $filename] ;# specific set tbl "put your data here - $n" ;# specific namespace eval [incr n] \ [list variable filename $filename fp $fp tbl $tbl] ;# variables specific set self [namespace current] interp alias {} ${self}::$n {} ${self}::dispatch $n return ${self}::$n } #---------------------------------- Method dispatcher proc filetbl::dispatch {this cmd args} { eval $cmd $this $args } #-----------------------------------Destructor proc filetbl::delete this { close [set ${this}::fp] ;# specific namespace delete $this interp alias {} [namespace current]::$this {} } #------------------------------- Further problem-specific methods come here: proc filetbl::test {this args} { puts [list hello $args] puts "tbl= [set ${this}::tbl]" } #------------------------------- Self-test if {[file tail [info script]] eq [file tail $argv0]} { set ft [filetbl::create [info script]] $ft test hello world ;# == filetbl::test $ft hello world $ft delete }