oopscopetclincr-tcl

How to call itcl::scope for an arbitrary object of the current class?


itcl::scope returns the full name of the specified member variable of $this.

How can I call itcl::scope for another object of the same class (not for $this)?

Here is a workaround.

itcl::class dummy {
    variable m_data

    method function { other } {
        if { [itcl::is object -class dummy $other] } {
            error "Invalid argument."
        }

        set name "@itcl $other [$other info variable m_data -name]"
        # OR
        set name [lreplace [itcl::scope m_data] 1 1 $other]

        puts "==== this is the name of m_data of of object $other: $name"
    }
}

But this is ugly, to put it mildly.

I suppose $other info variable m_data -name should return what I want, but it just omits the object's context.


Solution

  • There isn't a nice way to get that information, nor is it necessarily a good thing to make one. It's normally better to regard the variables of an object as being part of the implementation of that object, and not part of its interface. As such, external code shouldn't poke around inside like that; if it's important that something outside the object (including other members of the class) access the variables, write a method to return the reference to the variable (as generated with itcl::scope).

    itcl::class dummy {
        variable m_data
    
        protected method dataRef {} { itcl::scope m_data }
    
        method function { other } {
            if { [itcl::is object -class dummy $other] } {
                error "Invalid argument."
            }
    
            set name [$other dataRef]
    
            puts "==== this is the name of m_data of of object $other: $name"
        }
    }