Lua ignoring scope variable

Viewed 509

This might be a silly question, however, I don't know what is happening.

I have a simple script who fetches google time and I need to set it to the time global variable. So, inside the receive event, I print the time fetched and it works properly.

The problem is the variable time always as empty when called outside the event. Here is the code:

-- test.lua
time = ""

function getTime()
  conn = net.createConnection(net.TCP, 0)

  conn:connect(80,'google.com')
  conn:on("connection", function(conn, payload)
    conn:send("HEAD / HTTP/1.1\r\n"..
          "Host: google.com\r\n"..
          "Accept: */*\r\n"..
          "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
          "\r\n\r\n"
    )
  end)

  conn:on("receive", function(conn, payload)
    conn:close()
    time = string.sub(payload,string.find(payload,"Date: ")
       +6,string.find(payload,"Date: ")+35)
    end)
    print("testing: " .. time) -- WORKS!
end

getTime()
print("variable: ".. time)

Here is how I'm calling the function (using nodemcu-uploader terminal):

āžœ  test nu terminal
--- Miniterm on /dev/cu.wchusbserial1410  115200,8,N,1 ---
--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---

> dofile('lib/test.lua')
variable:
> testing: Sat, 20 May 2017 01:37:35 GMT

Any help would be really appreciated! Thanks

2 Answers
Related