Closure capture loop variables
Vladimir Panteleev via Digitalmars-d
digitalmars-d at puremagic.com
Wed Apr 29 18:19:44 PDT 2015
On Thursday, 30 April 2015 at 01:16:20 UTC, Freddy wrote:
> I understand that
> ----
> import std.stdio;
> void main(){
> int delegate() func;
> foreach(i;0..10){
> if(i==5){
> func= () => i;
> }
> }
> writeln(func());//9
> }
> ----
> captures the loop variable,but why does
> ----
> import std.stdio;
>
> void main(){
> int delegate() func;
> foreach(i;0..10){
> auto copy=i;
> if(i==5){
> func= () => copy;
> }
> }
> writeln(func());//should be 5
> }
>
> ----
> still print 9.
Because "copy" is still modified every time "i" is.
You can either put "copy" inside the "if":
----
import std.stdio;
void main(){
int delegate() func;
foreach(i;0..10){
if(i==5){
auto copy=i;
func= () => copy;
}
}
writeln(func());//should be 5
}
----
Or you can create a closure for each iteration:
----
import std.stdio;
void main(){
int delegate() func;
foreach(i;0..10){
(){
auto copy=i;
if(i==5){
func= () => copy;
}
}();
}
writeln(func());//should be 5
}
----
More information about the Digitalmars-d
mailing list