Imroy / pubsubclient

A client library for the ESP8266 that provides support for MQTT
MIT License
434 stars 115 forks source link

Can't pass 'this' to callback scope #9

Closed jmas closed 9 years ago

jmas commented 9 years ago

Hello. I'm not super-c++ programmer, but I found that I can't pass 'this' to lambda-function when I work with set_callback(). I want to do something like this:

        mqttClient.set_callback([this](const MQTT::Publish& pub){
            for (int i=0; i<eventsSize; ++i) {
                if (pub.topic() == events[i].name) {
                    events[i].callback(pub.payload_string());
                }
            }
        });

eventsSize, events is members of top-class scope where this code is present. In current PubSubClien.h I do not found way to work with eventsSize, events inside lambda-function.

So I did some modifications for PubSubClien.h:

public:
//typedef void(*callback_t)(const MQTT::Publish&);

//...

std::function<void(const MQTT::Publish&)> _callback;
//callback_t _callback;

//..

PubSubClient& set_callback(std::function<void(const MQTT::Publish&)> cb) { _callback = cb; return *this; }

And now I can pass variables of different scope to lambda-function.

I can do Pull-Request with this modifications. But if you know right way to pass variables of different scope to lambda-function - please tell how I can do this.

Imroy commented 9 years ago

It's simpler to just redefine callback_t using std::function.

jmas commented 9 years ago

@Imroy, Can you show some code how to do this. I'm noob in this. :(

UPD: Oh.. I see.. You just add source update. I'll try. Thanks.

UPD2: Yep. Now it working. Thanks a lot!

Imroy commented 9 years ago

Okay, good to hear you figured it out :)