Re: [Vala] for loop and closure (bug or big gotcha?)



On Wed, 2010-01-20 at 14:00 +0800, Nor Jaidi Tuah wrote:
Given this:

for (int i=0; i < 10; i++) {
    button[i].clicked.connect ((s) => {stdout.printf ("%d\n", i);});
}

all the buttons, when clicked, outputs 10.
i.e., the variable i is treated as non-local and shared
by all those closures.

Is this the correct semantic?

Yes.

If this is up for debate I would say that this is
a wrong semantic. Different iteration of the for loop
should use "different" i.

The scope of the variable `i` covers the whole `for` statement, not just
a single loop iteration (otherwise i++ at the end of each iteration
wouldn't make any sense). While it's true that this may cause mistakes,
we can't change this without breaking consistency. foreach loops should
be more convenient in that regard.

Jürg




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]