Version 0 of TclOO Accessors

Updated 2010-08-08 08:33:17 by manveru

I've tried adding a feature similar to the attr_accessor method found in Ruby to TclOO.

I have to admit that this is hacky at best, and not useful when not all your variables should be accessors, but it might serve as a starting point for others.

One thing I learned about TclOO is that it's very hard to add new methods to oo::define. After reading the source a bit I found that it uses a special stack frame.

This way it tries to restrict usage of its commands within a single stack level, which is impossible to use with uplevel.

I'm very skeptical about the need for such a restriction, given that it will lead to hacks similar to this one. It's definitely possible right now to execute oo::define commands within the oo::define script, so the restriction is weak at best. What would be needed for easy Pure-Tcl extensions of TclOO is availability of the class name or allowing uplevel into the stack frame.

package require TclOO

namespace eval oo {
  namespace eval define {
    proc accessor {args} {
      set name [lindex [dict get [info frame -2] cmd] 1]
      set accessors $args

      ::oo::define $name variable {*}$accessors
      foreach {accessor} $accessors {
        ::oo::define $name method $accessor {} "return $$accessor"
        ::oo::define $name method $accessor= {new} "return \[set $accessor \$new]"
      }
    }
  }
}

oo::class create Person {
  accessor first last

  constructor {} {
    set first Joe
    set last Doe
  }

  method name {} { return "$first $last" }
}

set a [Person new]
puts [$a name]

set b [Person new]
$b first= Jane
puts [$b name]