On Tuesday, 3 June 2014 at 05:40:44 UTC, Edwin van Leeuwen wrote:
On Monday, 2 June 2014 at 23:44:01 UTC, Rene Zwanenburg wrote:
On Monday, 2 June 2014 at 20:09:12 UTC, Edwin van Leeuwen wrote: As you may have guessed, a workaround is to copy the iteration variable yourself:

unittest {
   size_t delegate()[size_t] events;
   foreach(_i; 1..4 ) {
       auto i = _i;
       events[i] = { return i; };
   }
   assert( events[1]() == 1 );
}

This should work though it's less than ideal. There is an open bug report:
https://issues.dlang.org/show_bug.cgi?id=8621

Thanks for the suggestion and I just tried it, but it does not
work :(

In the original code were I discovered this problem I generated
the id with an outside function and that also didn't to work.

unittest {
    size_t delegate()[size_t] events;
    size_t i = 1;
    events[i] = { return i; };
    i = 2;
    events[i] = { return i; };
    i = 3;
    events[i] = { return i; };
    writeln( events[1]() );
    assert( events[1]() == 1 );
}

Explicitly removing the loop still causes the same issue. In that case I find it easier to understand, since it might be using the value of i at the end of the scope. In the foreach case (and especially when copying to a local variable) it is more puzzling to me.

Reply via email to