user869375
user869375

Reputation: 2419

Can't figure the statement logic in Lua (ESP8266 sample)

One of the program I came across on GitHub page for NodeMCU to toggle the LED was:

https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/webap_toggle_pin.lua

To simplify the code for understanding I guessed some variables were not being used and I could simply remove those lines. But to my utter surprise my code stopped working when I removed those lines from the code I uploaded to my ESP8266.

Can someone please help me figuring out the meaning of the following statement in the snippet below:

local _, _, method, path, var...........

As I understand, we are declaring 2 anonymous variables, and then additional variable called method, path and vars and setting the value of vars by doing a string search operation on request object.

But since we are not using the anonymous variables and method, which will be nil and hence path will also evaluate to nil since method is nil. So I removed the anonymous variables, method and path variables and upload the code. When I try to browse the page served by ESP, it throws error.

local buf = "";
    local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
    if(method == nil)then 
        _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); 
    end
    local _GET = {}
    if (vars ~= nil)then 
        for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do 
            _GET[k] = v 
        end 
    end

The error is

PANIC: unprotected error in call to Lua API (init.lua:27: attempt to concatenate global '_off' (a nil value))

Help me understand the complete meaning of the program.

Upvotes: 1

Views: 1101

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

_ is not an anonymous variable; it's a regular variable, but there is a convention to use _ to indicate variables you are ignoring in your code.

In this case, string.find returns start and end position of the first match, and then all captures (those groups you have in parentheses), so the author only needed the captured and start/end positions.

The fragment first checks if the URL is of the form method URL?parameters and gets the method, URL and parameters. The second check is for method URL (as it won't be matched by the first pattern match).

If the vars value is present, it gets parsed into key/value pairs as the query string.

Upvotes: 1

Related Questions