Skip to content

Instantly share code, notes, and snippets.

@schveiguy
Last active October 19, 2024 03:37
Show Gist options
  • Save schveiguy/b6b037bdfe74997743de81f8d3f4b92b to your computer and use it in GitHub Desktop.
Save schveiguy/b6b037bdfe74997743de81f8d3f4b92b to your computer and use it in GitHub Desktop.
Possible way to capture things in a loop?
auto stackFrame(T)(T rng)
{
static struct Apply
{
import std.range;
T rng;
int opApply(scope int delegate(ElementType!T) dg) {
foreach(e; rng) {
if(auto r = dg(e))
return r;
}
return 0;
}
}
return Apply(rng);
}
void main()
{
import std.stdio;
void delegate()[] dgs;
foreach(i; [1, 2, 3, 4]) {
dgs ~= () => writeln(i);
}
foreach(d; dgs) d(); // 4 4 4 4
dgs = null;
foreach(i; [1, 2, 3, 4].stackFrame) {
dgs ~= () => writeln(i);
}
foreach(d; dgs) d(); // 1 2 3 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment