[chuck-users] Doing something to all members of a class?

Scott Wheeler wheeler at kde.org
Tue Mar 13 10:53:01 EDT 2007


Kassen wrote:
> Say I have a class that has a member that's simply a integer used for 
> counting something.
>
> I'll have a few instances (ten or so) and they will all be counting 
> their own little thing on their own. So far so good. Now something 
> happens and I'd like to reset all the counters to zero after which 
> they should be independant again.
>
> How to go about this in a efficient way?


Here's an example implementation:

class Foo
{
    class ListNode
    {
        ListNode @ next;
        Foo @ item;
    }

    static ListNode @ first;
    static ListNode @ last;

    if(first == null)
    {
        new ListNode @=> first;
        first @=> last;
        this @=> first.item;
    }
    else
    {
        new ListNode @=> last.next;
        last.next @=> last;
        this @=> last.item;
    }

    0 => int value;

    fun void increment()
    {
        value++;
    }

    fun void print()
    {
        <<< value >>>;
    }

    fun static void reset()
    {
        for(first @=> ListNode @ node; node != null; node.next @=> node)
        {
            0 => node.item.value;
        }
    }
}

Foo a;
Foo b;
Foo c;

a.increment();

b.increment();
b.increment();

c.increment();
c.increment();
c.increment();

a.print();
b.print();
c.print();

Foo.reset();

a.print();
b.print();
c.print();

Which produces:

1 :(int)
2 :(int)
3 :(int)
0 :(int)
0 :(int)
0 :(int)

The first part is just an outline of a linked list.  Items are inserted 
into the list as they are created.  Then in the static function we go 
through the list and modify each instance.

The conceptual problem that you had is that static functions operate on 
*no* instance of a class rather than *all* instances of a class.  Static 
functions can only access static variables since the others are not 
available (since there's no instance there for them to access).

-Scott


More information about the chuck-users mailing list