Jump to content

Add a variable to a class instance at runtime: Difference between revisions

→‎{{header|Tcl}}: Do it in an alternative way
(→‎{{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}}
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.