reo7sp / tgbot-cpp

C++ library for Telegram bot API
http://reo7sp.github.io/tgbot-cpp
MIT License
1.01k stars 245 forks source link

an enclosing-function local variable cannot be referenced in a lambda body #253

Closed miannoodle01 closed 1 year ago

miannoodle01 commented 1 year ago

Hello all! I'm looking for a way to see if the main server is busy, divert the job to other bot to handle, but on any attempt that I want to declare variables to write the user message to it for future handling, it throws the error i wrote on the title, which it's complete form is: an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list For example I want to do such thing: bot.getEvents().onAnyMessage([&bot] (Message::Ptr message) { string receivedText = message -> text; if ( /* code to see if server is busy*/) { bot.getApi().sendMessage(/* other bot id */, receivedMessage); }); How can I solve this? Thanks!

llnulldisk commented 1 year ago

Hi!

The variable receivedMessage is undefined in the lambda. You need to capture it, like you did with bot or you need to declare this variable inside the lambda. You can automatically capture all the neccessary variables with [&].

miannoodle01 commented 1 year ago

Yes! How can I do that? Can you give an example please? How can I declare variables inside lambda?

llnulldisk commented 1 year ago

Have you already defined receivedMessage outside of the lambda? If yes, you can capture it with [&bot, &receivedMessage] or with [&]. If not, you have to define the variable inside the lambda like you normally would do

miannoodle01 commented 1 year ago

@llnulldisk Thanks man fixed that as you said, but for whom the understand of his word is little hard, my friend saying to change code as below: string test = "test"; bot.getApi().onCommand("test", [&bot, &test] (Message::Ptr message) { bot.getApi().sendMessage(message -> chat -> id, test) });

Then it will work fine!