Anonymous user
Add a variable to a class instance at runtime: Difference between revisions
Add a variable to a class instance at runtime (view source)
Revision as of 13:33, 25 November 2009
, 14 years ago→{{header|Tcl}}: Do it in an alternative way
m (→{{header|Mathematica}}: clarify) |
(→{{header|Tcl}}: Do it in an alternative way) |
||
Line 383:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<br>
{{works with|Tcl|8.5}} and the [http://wiki.tcl.tk/TclOO TclOO package]
Line 413:
now
%</lang>
An alternative approach is to expose the (normally hidden) <code>varname</code> method on the object so that you can get a handle for an arbitrary variable in the object.
<lang tcl>% oo::class create summation {
constructor {} {
variable v 0
}
method add x {
variable v
incr v $x
}
method value {{var v}} {
variable $var
return [set $var]
}
destructor {
variable v
puts "Ended with value $v"
}
}
::summation
% set s [summation new]
% set s2 [summation new]
% oo::objdefine $s export varname
% # Do the monkey patch...
% set [$s varname time] "now"
% $s value time
now
% # Show that it is only in one object...
% $s2 value time
can't read "time": no such variable</lang>
{{omit from|ALGOL 68}}
|