Let's get the semantic around closure fixed.
Jesse Phillips
Jesse.K.Phillips+D at gmail.com
Wed May 19 14:24:57 UTC 2021
On Tuesday, 18 May 2021 at 16:47:03 UTC, deadalnix wrote:
> Long story short: https://issues.dlang.org/show_bug.cgi?id=21929
>
> Closure do not respect scope the way they should. Let's fix it.
After Walter's post I definitely see what is happening.
```dlang
for (int i = 0; i < 10; i++) {
int index = i;
dgs ~= () {
import std.stdio;
writeln(index);
};
}
```
When this loop concludes, the value of `i` is 10 and the value of
index is 9 (as shown from your output).
This is because within the `for` logic `i` was increased and it
determined `10 < 10` is false. This means the `for`body is not
executed again leaving `index` at 9.
I don't know why compiler magic you would expect is "correct"
here. We can't say `i` should be 9 as the loop would not have
exited then. We certainly don't want `index` to be 10 as that
would mean the loop expected on more time than it was defined to.
Untested
```dlang
auto i;
auto index;
for (i = 0; i < 10; i++) {
index = i;
dgs ~= () {
import std.stdio;
writeln(i);
writeln(index);
};
}
```
More information about the Digitalmars-d
mailing list