Cannot change value of variable in a button press lambda

I have declared variable chosenBlockTexture.
I am generating a dozen of buttons by reading a dictionary and creating the buttons with their touch event callback being setting the chosenBlockTexture variable to the dictionary’s key value.

for (auto it : blockDict) {
    auto newBlockButton = Button::create("button-block-basic.png", "button-block-basic.png", "button-block-basic.png");
    auto buttonImage = Sprite::create(it.first);

    newBlockButton->setPosition(Vec2(76 * blockDictIter, 64));
    buttonImage->setPosition(Vec2(76 * blockDictIter, 64));
    buttonImage->setGlobalZOrder(2);
    buttonImage->setScale(0.75);
    
    

    newBlockButton->addTouchEventListener([&](Ref* sender, Widget::TouchEventType type) {
        switch (type)
        {
        case ui::Widget::TouchEventType::BEGAN:
            break;
        case ui::Widget::TouchEventType::ENDED:
            chosenBlockTexture = it.first;
            break;
        default:
            break;
        }
     });

    blockDictIter++;

    newBlockButton->setGlobalZOrder(1);
    this->addChild(newBlockButton);
    this->addChild(buttonImage);
}

When I wrote the code in VS, it did not point to any errors in the code, but when I ran the project and tried clicking on one of the buttons, it gave me this error:
image

Please help because I have been trying to fix this for the last 2 days!!

@lazarpuppet Why do not you set a breakpoint inside this lambda, to see what you have in used varriables?
It looks like ‘it’ - is stack value whose address is corrupted when lamda calling occures.
If ‘it.first’ is string it should be passed by value as closure in you case.

How would I go on about doing that?

Try the following simple changes to check if the issue in iterator.
(It is supposed that chosenBlockTexture is the member of ‘this’ and type of it.first is std::string)

for (auto it : blockDict) {
auto newBlockButton = Button::create(“button-block-basic.png”, “button-block-basic.png”, “button-block-basic.png”);
auto buttonImage = Sprite::create(it.first);

newBlockButton->setPosition(Vec2(76 * blockDictIter, 64));
buttonImage->setPosition(Vec2(76 * blockDictIter, 64));
buttonImage->setGlobalZOrder(2);
buttonImage->setScale(0.75);

auto text_file = it.first;

newBlockButton->addTouchEventListener([this, text_file](Ref* sender, Widget::TouchEventType type) {
    switch (type)
    {
    case ui::Widget::TouchEventType::BEGAN:
        break;
    case ui::Widget::TouchEventType::ENDED:
        chosenBlockTexture = text_file;
        break;
    default:
        break;
    }
 });

blockDictIter++;

newBlockButton->setGlobalZOrder(1);
this->addChild(newBlockButton);
this->addChild(buttonImage);

}

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.