In my opinion,
set a [dict create]
@ a.first = "Fred"
@ a.last = "Flintstone"
@ a.count = 0
set b [@ a.last]
is not necessarily better than:
set a {
first Fred
last Flintstone
count 0
}
set b [dict get $a last]
To define methods only valid until the dict goes out of scope, here is
an equivalent alternative without apply:
# define a method stored in the dict
proc dictMethod {dictName name args body} {
upvar $dictName dict
dict set dict method_$name [list $args $body]
return
}
# call method in dict
proc dictCall {dictName name args} {
upvar $dictName this
lassign [dict get $this method_$name] method_args body
if {[llength $args] != [llength $method_args]} {
error "args should be: $method_args"
}
# assign arguments to variables
foreach arg $args method_arg $method_args {
set $method_arg $arg
}
eval $body
}
After these two helper functions, it is possible to write:
set a {
first Fred
last Flintstone
count 0
}
# define method 'greet' in dict 'a' with argument 'name'
dictMethod a greet {name} {
puts "[dict get $this first] [dict get $this last] says hello, $name"
dict set this count [expr [dict get $this count]+1]
return
}
# call the method
dictCall a greet Barney
Since the method is stored inside the dict (as field method_$name), as
soon as the dict goes out of scope, the method also goes out of scope.
So it's an alternative implementation, without syntactic sugar or
apply.
- Peter
------------------------------------------------------------------------------
_______________________________________________
Tcl-Core mailing list
Tcl-...@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/tcl-core