On Fri, Jul 6, 2012 at 3:06 PM, Timon Gehr <timon.gehr@gmx.ch> wrote:

It is simple. Variable declarations introduce a new variable. Closures
that reference the same variable will see the same values.

----

foreach(i; 0..3) { functions~={writeln(i);}; }

is the same as

for(int i=0;i<3;i++) { functions~={writeln(i);}; }

is the same as

{int i=0;for(;i<3;i++) { functions~={writeln(i);}; }}

is the same as

{
    int i=0;
    { functions~={writeln(i);}; }
    i++;
    { functions~={writeln(i);}; }
    i++;
    { functions~={writeln(i);}; }
    i++;
}


----

foreach(i; 0..3){ int j=i; functions~={writeln(j);}; }

is the same as

for(int i=0;i<3;i++){ int j=i; functions~={writeln(j);}; }

is the same as

{int i=0;for(i<3;i++){ int j=i; functions~={writeln(j);}; }

is the same as

{
    int i=0;
    { int j=i; functions~={writeln(j);}; }
    i++;
    { int j=i; functions~={writeln(j);}; }
    i++;
    { int j=i; functions~={writeln(j);}; }
    i++;
}

----

I think it is quite intuitive.


Understood, thanks.