Strange closure behaviour
Emmanuelle
VuLXn6DBW at PPtUm7TvV6nsw.com
Sat Jun 15 01:21:46 UTC 2019
On Saturday, 15 June 2019 at 00:30:43 UTC, Adam D. Ruppe wrote:
> On Saturday, 15 June 2019 at 00:24:52 UTC, Emmanuelle wrote:
>> Is it a compiler bug?
>
> Yup, a very longstanding bug.
>
> You can work around it by wrapping it all in another layer of
> function which you immediately call (which is fairly common in
> javascript):
>
> funcs ~= ((x) => (int i) { nums[x] ~= i; })(x);
>
> Or maybe less confusingly written long form:
>
> funcs ~= (delegate(x) {
> return (int i) { nums[x] ~= i; };
> })(x);
>
> You write a function that returns your actual function, and
> immediately calls it with the loop variable, which will
> explicitly make a copy of it.
Oh, I see. Unfortunate that it's a longstanding compiler bug, but
at least the rather awkward workaround will do. Thank you!
More information about the Digitalmars-d-learn
mailing list