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:
local function build_request()
local payload = "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"
return payload
end
local function connect(sck)
local post_request = build_request()
sck:send(post_request)
end
local function receiver(sck, callback)
time = string.sub(callback,string.find(callback,"Date: ")
+6,string.find(callback,"Date: ")+35)
print(time) -- WORKS!
end
local function disconnect(sck)
sck = nil
end
function fetch()
socket = net.createConnection(net.TCP, 0)
socket:on("receive", receiver)
socket:connect(80, 'google.com')
socket:on("connection", connect)
socket:on("disconnection", disconnect)
end
print(fetch())
print(time)
Here is how I'm calling the function (using nodemcu-uploader terminal):
➜ temperature 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')
> Mon, 22 May 2017 00:35:10 GMT
As we can see, the print(time) does not print. How could I have a function that returns the time variable value?
Any help would be really appreciated! Thanks