Delegate, scope and associative array

Edwin van Leeuwen via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 2 13:09:09 PDT 2014


I'm probably missing something basic, but I am confused by what 
is going on in the following code.

unittest {
     size_t delegate()[size_t] events;
     foreach( i; 1..4 ) {
         events[i] = { return i; };
     }
     writeln( events[1]() ); // This outputs 3
     assert( events[1]() == 1 );
}

I thought that i should be copied from the local scope and 
therefore when I call events[1]() the return value should be 1, 
but in this case it is 3 (it always seems to be the last value of 
i in the loop).

Cheers, Edwin




More information about the Digitalmars-d-learn mailing list