Closure capture loop variables

via Digitalmars-d digitalmars-d at puremagic.com
Fri May 1 05:31:42 PDT 2015


On Thursday, 30 April 2015 at 12:55:18 UTC, Vladimir Panteleev 
wrote:
> On Thursday, 30 April 2015 at 12:01:32 UTC, Marc Schütz wrote:
>> On Thursday, 30 April 2015 at 05:23:55 UTC, Vladimir Panteleev 
>> wrote:
>>> On Thursday, 30 April 2015 at 03:58:44 UTC, Freddy wrote:
>>>> On Thursday, 30 April 2015 at 01:19:45 UTC, Vladimir 
>>>> Panteleev wrote:
>>>>> Because "copy" is still modified every time "i" is.
>>>> But shouldn't copy be redeclared every loop iteration (or 
>>>> the compiler could pretend to redeclare it).
>>>
>>> No, it will have the same address every time.
>>
>> The current behaviour is wrong:
>> https://issues.dlang.org/show_bug.cgi?id=2043
>> https://issues.dlang.org/show_bug.cgi?id=8621
>
> These are slightly different problems. I think Freddy's 
> programs are working as designed.
>
> D closures should work in the same way as, e.g., JS closures. 
> Try rewriting the program in JavaScript. If it behaves in the 
> same way, it's not a D bug.

I don't think so. JS is not comparable, because it's scoping 
rules are different from D. Closures should capture the variable, 
not its memory location. And both `i` and `copy` are distinct 
variables in each loop iteration, they just happen to share the 
same location, because they have non-intersecting lifetimes.


More information about the Digitalmars-d mailing list