Post your best Lua script examples here

User avatar
By bicli
#8334 Hello guys,

I am having a problem, where I hope somebody can help me out, since I am not an expert on Lua.
I put the following code into "init.lua" file

Code: Select allmqtt.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.4.2", 1984, 0, function(conn) print("connected") end)
m:subscribe("hello_world",0, function(conn) print("subscribe success") end)
m:publish("test_publish","hello",0,0, function(conn) print("sent") end)


But when I restart the ESP8266, console says:
lua: init.lua:2: attempt to index global 'mqtt' (a nil value)

What am I doing wrong here?

PS: I flashed the device with ESP8266Flasher.exe from https://github.com/nodemcu/nodemcu-flasher
Thank you
User avatar
By bicli
#8336 Oh that is a copy paste mistake of mine. It should have been:
Code: Select allm = 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.4.2", 1984, 0, function(conn) print("connected") end)
m:subscribe("hello_world",0, function(conn) print("subscribe success") end)
m:publish("temperature","hello",0,0, function(conn) print("sent") end)

And the error is about 'mqtt', but what actually doesn't he like about it?