1

I have maybe a weird question but I need to know this. Im creating a lua script to connect esp8266 and my mqtt broker. The example script is very straight forward.

m = mqtt.Client("clientid", 120, "user", "password")

m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)

m:on("message", function(conn, topic, data) 
  print(topic .. ":" ) 
  if data ~= nil then
    print(data)
  end
end)

m:connect("192.168.11.118", 1880, 0, function(conn) 
    print("connected") 
end)

m:subscribe("/topic",0, function(conn) 
    print("subscribe success") 
end)

m:publish("/topic","hello",0,0, function(conn) 
    print("sent") 
end)

m:close();

But... there is one thing I can't get over. That is the "con" and "conn" parameter? It looks like an instance or something, but there is no such a thing defined. Can somebody explain this to me?

1 Answer 1

1

From the docs you can find that the client's on() method registers a callback where the first param is the client itself. For your convenience (and in case the link dies) I have copied the relevant information below:

mqtt.client:on()

Description

register callback function to event.

Syntax

mqtt:on(event, function(client, [topic], [message]))

Parameters

event
string, which can be: "connect", "message", "offline"

function(client, [topic], [message])
callback function. The first param is the client. If event is "message", the 2nd and 3rd param are received topic and message in string.

Returns

nil.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks. But where is that client defined? There is just instance "m". And why there is once "con" and once "conn"? Everything is working, I just want to fully understand.
m is the client instance, which was created when you called mqtt.Client(...) and that is exactly what is being passed to the callback. con and conn is just what you have named the parameter. Try adding print(con==m) into one of the callbacks and you'll see they are the same.
@jevniky if this is solved then please accept this answer so that StackOverflow can mark it solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.