an enclosing-function local variable cannot be referenced in a lambda body
miannoodle01 opened this issue · comments
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!
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 [&]
.
Yes! How can I do that? Can you give an example please? How can I declare variables inside lambda?
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
@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!