Re: Lambda capture by value

2020-02-24 Thread Steven Schveighoffer via Digitalmars-d-learn
On 2/24/20 3:32 PM, H. S. Teoh wrote: To fix this, copy the value of 'i' to a local variable inside the loop body, then the lambda will correctly capture a unique per-iteration instance of the variable. Like this: foreach (i; iota(5)) { auto _i = i; printers[i] = ()

Re: Lambda capture by value

2020-02-24 Thread Elronnd via Digitalmars-d-learn
printers[i] = () { write(i); }; I know it looks silly but if you make that: printers[i] = (int i) { return () { write(i); }; }(i); it will do what you want. Or, the slightly prettier (imo) printers[i] = ((i) => () => write(i))(i); Or, if you need to force it to

Re: Lambda capture by value

2020-02-24 Thread H. S. Teoh via Digitalmars-d-learn
On Mon, Feb 24, 2020 at 07:50:23PM +, JN via Digitalmars-d-learn wrote: > import std.range; > import std.stdio; > > alias NumberPrinter = void delegate(); > > NumberPrinter[int] printers; > > void main() > { > foreach (i; iota(5)) > { > printers[i] = () { write(i); }; >

Re: Lambda capture by value

2020-02-24 Thread kinke via Digitalmars-d-learn
On Monday, 24 February 2020 at 19:50:23 UTC, JN wrote: foreach (i; iota(5)) { printers[i] = () { write(i); }; } This allocates 1 closure and generates 1 lambda, so all printers are identical delegates. You could use a static foreach: NumberPrinter[] printers; static

Re: Lambda capture by value

2020-02-24 Thread JN via Digitalmars-d-learn
On Monday, 24 February 2020 at 20:00:20 UTC, Adam D. Ruppe wrote: On Monday, 24 February 2020 at 19:50:23 UTC, JN wrote: foreach (i; iota(5)) { printers[i] = () { write(i); }; I know it looks silly but if you make that: printers[i] = (int i) { return () { write(i);

Re: Lambda capture by value

2020-02-24 Thread Adam D. Ruppe via Digitalmars-d-learn
On Monday, 24 February 2020 at 19:50:23 UTC, JN wrote: foreach (i; iota(5)) { printers[i] = () { write(i); }; I know it looks silly but if you make that: printers[i] = (int i) { return () { write(i); }; }(i); it will do what you want. This is something that used to

Lambda capture by value

2020-02-24 Thread JN via Digitalmars-d-learn
import std.range; import std.stdio; alias NumberPrinter = void delegate(); NumberPrinter[int] printers; void main() { foreach (i; iota(5)) { printers[i] = () { write(i); }; } foreach (i; iota(5)) { printers[i](); } } This prints 4 4 4 4 4. How to make