这可能是一个愚蠢的问题,但是,我不知道发生了什么。Lua忽略范围变量
我有一个简单的脚本获取谷歌时间,我需要将它设置为time
全局变量。因此,在receive
事件中,我打印了取回的时间并且它正常工作。
问题是变量time
在事件外被调用时总是空的。下面是代码:
-- 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)
这里是我如何调用该函数(使用nodemcu-上传终端):
➜ 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
任何帮助将非常感激! 谢谢
当心!这会造成内存泄漏,因为您在'connection'和'receive'回调中重新使用'conn'变量。请参阅http://stackoverflow.com/a/37379426/131929。 –
@MarcelStör..在事件结束时设置为'nil'可以解决这个问题吗? – hugalves