Delegate, scope and associative array

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 3 00:00:34 PDT 2014


On 06/02/2014 10:40 PM, 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.

Here is a workaround:

unittest {
     size_t delegate()[size_t] events;

     auto makeClosure(size_t i) {
         return { return i; };
     }

     foreach( i; 1..4 ) {
         events[i] = makeClosure(i);
     }

     assert( events[1]() == 1 );
}

void main()
{}

Ali



More information about the Digitalmars-d-learn mailing list