Local variable inside delegate literal
downs
default_357-line at yahoo.de
Wed Dec 23 04:13:32 PST 2009
Daniel wrote:
> I'm writing some gui code, and am currently trying to make something equivalent to this:
>
> int delegate()[] funcs;
> funcs.length = 3;
>
> foreach(i, ref f; funcs)
> {
> f = int() { return i; }
> }
>
> foreach(f; funcs)
> {
> writeln(f());
> }
>
> Prints:
> 3
> 3
> 3
>
> I want it to print
> 0
> 1
> 2
>
> Is there anyway to get this behaviour using delegate literals initialized with a runtime loop?
This is how you do it in 1.0:
import std.stdio, std.bind;
void main() {
auto funcs = new int delegate()[3];
foreach (i, ref f; funcs)
f = bind((int i) { return i; }, i).ptr();
foreach (f; funcs)
writefln(f());
}
--outputs--
0
1
2
More information about the Digitalmars-d
mailing list