Post your best Lua script examples here

User avatar
By bradvoy
#6904 Here's an update. This one will parse parameters from a URL-encoded form POST. It also allows you to send a response with a content-type other than HTML, for example json. And I think it will solve the problem jankop ran into with an invalid request causing a reset.

Here's an example showing how to return JSON and how to use parameters sent via a form with POST:
Code: Select allpages = {}
pages["/name"] = function(request)
  return '<html><head><title>Form Test</title></head><body>' ..
    '<form method="POST" action="/welcome">' ..
    'What is your name? <input name="n"/>' ..
    '<input type="submit" />' ..
    '</form></body></html>'
end 
pages["/welcome"] = function(request)
  name = request.form["n"]
  return "<html><head><title>Welcome</title></head><body><p>Welcome " .. name .. ".</p></body></html>"
end
pages["/json"] = function(request)
  return '{ "temperature": 82, "barometer": 30.2 }', 'application/json'
end
w = startWeb({pages = pages})
Attachments
(2.27 KiB) Downloaded 813 times
User avatar
By jankop
#6922
Code: Select allRequest received:    GET   /name
Request received:    POST   /welcome
PANIC: unprotected error in call to Lua API (demox.lua:10: attempt to concatenate global 'name' (a nil value))
PANIC: unprotected error in call to Lua API (attempt to concatenate a userdata value)
F)ŤţŠâ@H!¦1§D¦H9Ś
˙BCá
NodeMCU 0.9.5 build 20150107  powered by Lua 5.1.4
lua: cannot open init.lua


The message I received after I submit parameter "name" with your example.

I had to return to the previous version httpServer.lua. The new version is some unstable. I can not figure out why almost unreasonably restarts every a legal GET request.
Is there also any mistake in parser, some illegal queries will cause an internal lua error. The second problem is that server disconnects after a shorter or longer time from the AP and not communicate via WiFi. But that's probably not a problem of the program, but the of the system. I meet with it repeatedly.
User avatar
By bradvoy
#7160 jankop, that's a cool demo page you've created.

I'm unable to duplicate the problems you've experienced with the latest version of httpServer.lua. I've loaded the /name page and submitted the form dozens of times without encountering any errors or spontaneous restarts. I'm currently using the 20150107 version of the firmware.