Search code examples
tclitcl

How to resource the itcl classes to without starting a tcl shell


With this Tcl script: A.tcl

itcl::class ::A {
    variable list1 {}
    public method getList {} {
        return $list1
    } 
}

I do this:

  • Start the tcl shell and interactively do source A.tcl
  • then make changes to getList method in A.tcl
  • To make the changes effective, I do re-source the file A.tcl
  • When I re-source, I get the following error
% source /home/manid/scripts/test.tcl
class "A" already exists

How can i overcome this error? Is there a way to get the latest changes in the class definition without exiting the shell?


Solution

  • You need to write your code somewhat differently. In particular, you have to put the definitions of the body of the methods (which can be repeated) outside the declaration of the class (which can't be repeated). Then, you do a conditional class creation (with itcl::is class as the tester) and use itcl::body to actually provide the method definitions.

    According to these principles, rewriting your A.tcl to be:

    if {![itcl::is class ::A]} {
        itcl::class ::A {
            variable list1 {}
            # *Dummy* method body; method must exist, but may be empty
            public method getList {} {}
        }
    }
    
    itcl::body ::A::getList {} {
        return $list1
    }
    

    would allow you to source that multiple times to change the method bodies however you wanted. This doesn't give you freedom to change everything (e.g., the variable declarations and scope rules are fixed); you need to switch to something like TclOO to get that sort of flexibility.