How to avoid variable capturing in `foreach` loop with lambdas?

Tejas notrealemail at gmail.com
Fri Jan 6 02:22:28 UTC 2023


On Thursday, 5 January 2023 at 22:49:01 UTC, thebluepandabear 
wrote:
>> Have fun reading this :
>>
>> https://issues.dlang.org/show_bug.cgi?id=21929
>
> Thanks for the code suggestion although it still doesn't fix 
> the bug. I am curious as to what those brackets do as well.

Okay, my bad for writing the wrong code, the correct one is:
```d
  foreach (BoardSize boardSizeIter; arr) (Boardsize boardSize){ // 
notice the brackets and I changed the variable names a little
      Button button = new Button();
      button.text = format("%sx%s", boardSize[0], boardSize[1]);
      button.onButtonClick = {

  eventHandler.settingsWindow_onBoardSizeButtonClick(boardSize);
      };
      button.onButtonClick();
      _boardSizeRow.addChild(button);
  }(boardSizeIter) // notice the brackets and that I changed the 
name of you first foreach argument
```

This will do the same thing as HS Teoh and Tsbockman's code did : 
create a copy of the value that is currently present in one 
particular iteration of the `foreach` by creating a function 
literal that takes your `struct` as a paramter. This works 
because structs are value types, so passing it to the function 
creates a copy.



More information about the Digitalmars-d-learn mailing list