Scott James Walter
Scott James Walter

Reputation: 427

TCL Array: Data Not Persistent?

I'm going through a crash course in TCL and I'm running into a problem with arrays in TCL. I have two classes, say A and B. In class B I have a method that updates a local array. The format for the array is something like this:

filterData(1) = 23904890234009
filterData(2) = 28974501002990
filterData(3) = 69398018930453 

... and it stops there. Only 3 indices. In class A, I instantiate a B object and run a method on it to update the local array. The method inside class B looks like this:

method addData {} {
    lappend filterData($type) $data
}

The $type variable is a number 1-3, and the $data variable is a string of numbers. Whenever I run this method and print the arrays contents, it has nothing in it, like it's a new array. What's strange is I have other local variables (lists, strings) in class B that I do the same operation to that are persistent unlike this array which seems to be resetting itself. Any ideas as to how I may be handling this incorrectly? If more info is needed, I can provide.

Upvotes: 0

Views: 138

Answers (2)

Scott James Walter
Scott James Walter

Reputation: 427

I ended up figuring out the problem yesterday. The problem was with my array declaration. Before I had:

array set filterData {}

...and only that at the top of my code. I then changed it to:

variable filterData
array set filterData {}

and the variable was then saving to the class object I had instantiated of it on subsequent calls to methods belonging to that class. It was a silly mistake on my part.

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137577

In Itcl, the behaviour with this sort of thing depends critically on your variable declarations. Here's an example with a simple variable declaration

% package req Itcl 4
4.0b7
% itcl::class Foo {
    variable filterData
    method addData {type data} {
        lappend filterData($type) $data
    }
}
% Foo a
a
% a addData 1 2
2
% a addData 1 3
2 3
% Foo b
b
% b addData 1 4
4
% a addData 1 5
2 3 5

Notice how a and b don't share their filterData array? It's an instance variable. For a class variable that is shared between many instances, you instead use common to declare them:

% package req Itcl 4
4.0b7
% itcl::class Foo {
    common filterData
    method addData {type data} {
        lappend filterData($type) $data
    }
}
% Foo a
a
% a addData 1 2
2
% a addData 1 3
2 3
% Foo b
b
% b addData 1 4
2 3 4
% a addData 1 5
2 3 4 5

See how I changed one word in the declaration and got the shared variable (shared array really)?

Upvotes: 2

Related Questions