Why do I get “Lexical with name '$x' does not exist in this frame” when using “will leave”?

Viewed 147

I have the following Raku code:

class Thing {
    method close {
        say "closed";
    }
};

for 1..1000 {
    my $x will leave { .close } = Thing.new;
}

Running it, I get the error:

Lexical with name '$x' does not exist in this frame
  in block <unit> at c.raku line 7

Interestingly, this only happens if the number of iterations is high enough (with 500 or 100, I do not get any error messages).

If I change the body of the cycle to

my $x = Thing.new;
LEAVE $x.close;

then everything works without errors as well.

What is happening here? Did I misunderstand the will leave construct? (It seems to me the two versions should be equivalent.)

EDIT: Further observation – when running the code multiple times, the error appears nondeterministically. This suggests that the problem is somehow connected to garbage collection, but I am still confused as to what actually happens here.

I am using Rakudo v2021.03.

1 Answers
Related