Closures and loop scope

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Tue Jun 4 15:06:39 PDT 2013


On Tue, 04 Jun 2013 23:48:32 +0200
Timon Gehr <timon.gehr at gmx.ch> wrote:

> On 06/04/2013 11:38 PM, Nick Sabalausky wrote:
> > On Tue, 04 Jun 2013 23:24:51 +0200
> > Timon Gehr <timon.gehr at gmx.ch> wrote:
> >>
> >> 'a' refers to a different location for every loop iteration. This
> >> is a language change in 2.063.
> >>
> >
> > foreach(a;0..5)
> >      writeln(&a);
> >
> > For me, that prints the same address five times in both 2.062 and
> > 2.063.
> 
> It does not matter. The lifetimes of the different a's do not overlap.
> 

Ok, I see what you mean now: Closures are expected to capture the
current scope, not just the current function's scope (which wouldn't
have been right anyway as it would have prevented access to the loop
variable).

Ie:

    int delegate() dg;

    {
        int a = 2;
        dg = () => a;
    }

    int a = 100;
    writeln(dg());

That prints 2, as expected.

I hadn't thought of that. With that in mind, then yes, the OP's example
should print 0, 1, 2, 3, etc, not all 5's.



More information about the Digitalmars-d mailing list