Reputation: 21
I'm new to object-oriented programming in TCL. I installed ActiveTCL 8.6 which includes the package TclOO in order to use classes and objects in TCL. I would like to create an object and call various procedures in order to use it. For instance, I tried the following piece of code:
oo::class create Test {
method func {} {
puts "Hello World!"
}
}
proc speak { myObj } {
myObj func
}
Test create testObj
testObj func; # This prints "Hello World!"
speak testObj; # This raises an error -> invalid command name "myObj"
What should I do in order to use the object testObj in the "speak" procedure?
Upvotes: 2
Views: 717
Reputation: 137567
When you pass an object, you're actually passing the name of the object. The variable, the formal parameter, is then holding the name and you dereference the variable to use the object (and not the variable itself):
proc speak { myObj } {
$myObj func
}
Note that you can also use a one-argument set
to read the variable; this code below is equivalent to that above, but more long-winded:
proc speak { myObj } {
[set myObj] func
}
It's also possible to make an alias to the object that can then have any name you want it to, but this is not recommended for procedures as such names are always effectively global.
# Don't do this!
proc speak { myObj } {
interp alias {} $myObj {} myObj
myObj func
}
This makes a lot more sense when you're passing an object into a constructor or storing it in a namespace that has many commands that may use it. (In fact, rename
the object into the other object or namespace and the object will become managed by the lifetime of the entity which you moved it into; this is the simplest, most recommended way of doing UML Composition, and is used extensively inside the implementation of TDBC drivers. The key is the lifetime; procedure calls aren't usually things you want to limit passed-in objects' lifetime to.)
Upvotes: 4