On Mon, Sep 17, 2007 at 08:25:01AM +0000, Henrik Grubbstr�m (Lysator) @ Pike (-) developers forum wrote:
function(:int) X1 = X()->inc; function(:int) X2 = X()->inc;
my gut feeling tells me that i'd expect two counters here. these two inc functions are not the same.
it would be different if the function itself were declared static: class X { static int inc() { static int counter; return counter++; } }
now i'd expect inc() to be shared accross all instances of X
I believe that the most useful would be to store the variable in the closest surrounding scope (ie X1:0,1 X2:0 for both of the above), and then have some extra syntax for specifying some other scope. The question is what the syntax should be?
is that syntax needed? wouldn't that already be solved if you declare the variable in the scope where you want it?
btw, what is the difference between a static variable in a function
class X { int inc() { static int counter; return counter++; } }
and just using a variable in the class scope or a closure?
class X { int counter; int inc() { return counter++; } }
both give the same result with:
int main() { function(:int) X1 = X()->inc; function(:int) X2 = X()->inc; write("X1:%O,%O\n" "X2:%O\n", X1(), X1(), X2()); }
so having static inside a function is really just a disguised object variable. except that other functions can't reach that variable, so there may be some sense to that, but in general i think static variables on the class level are more interesting.
greetings, martin.