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] = ()
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 r
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); };
> }
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 forea
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); };
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 b
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