yaro
yaro

Reputation: 33

TCLOO: Private Method And Method As Callback

Using Tcloo (self compiled TCL 8.6.7) I implemented a client socket.

I have the folowing issues:

  1. I how can make a method private when declare using only oo::create class
  2. How can I register the method of the class as the event callback for the socket. I have tried the following:

    chan event $sock readable [list readSocket $sock] Error: invalid command name "readSocket"...

    chan event $sock readable [list [self] readSocket $sock] Error: invalid command name "self"...

Any help will be appreciated.

Upvotes: 0

Views: 723

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13282

Methods with names that start with a lower-case letter are public, others are private. You can also use export and unexport.

oo::class create C {
    method foo args {}  ;# public

    method Bar args {}  ;# private

    method Baz args {}  ;# private
    export Baz          ;# now it's public

    method quux args {} ;# public
    unexport quux       ;# now it's private
}

As usual in Tcl you can use a variety of methods to define a callback. You need to know which namespace the object uses and qualify the my method to that namespace.

From within an object, the namespace can be introspected using self namespace or namespace which my, but the easiest way is to use namespace code:

namespace code {my readSocket $sock}
namespace code [list my readSocket $sock]

The difference between these is that in the upper line, $sock gets variable substituted when the callback is called, and in the second line, it gets substituted when the callback is defined. The result of this invocation is a namespace-independent command prefix that can be executed by any evaluating command. Note that sock must be visible in the context: a regular namespace variable isn't visible unless variable has been called on it; a TclOO class level variable is visible inside all methods.

From outside the object, the object's namespace can be identified using info object namespace:

list [info object namespace $obj]::my readSocket $sock

(Evaluates sock in caller namespace at the time the callback is defined.)

Documentation: info, list, my, namespace, oo::class, oo::define, Summary of Tcl language syntax

Upvotes: 1

Related Questions