require("internet").request now returns a function object

The function object can be called to read from the stream, same usage as before
But the object also exposes the request handle userdata, to allow calling close for example:

```
local request = require("internet").request("http://www.google.com")
print(request()) -- same as before
request:close() -- clean up resources now, as opposed to waiting for gc
```

closes #2255
This commit is contained in:
payonel 2017-02-04 14:48:47 -08:00
parent afff699dff
commit d8471278ba

View File

@ -11,10 +11,10 @@ function internet.request(url, data, headers)
checkArg(2, data, "string", "table", "nil") checkArg(2, data, "string", "table", "nil")
checkArg(3, headers, "table", "nil") checkArg(3, headers, "table", "nil")
local inet = component.internet if not component.isAvailable("internet") then
if not inet then
error("no primary internet card found", 2) error("no primary internet card found", 2)
end end
local inet = component.internet
local post local post
if type(data) == "string" then if type(data) == "string" then
@ -31,7 +31,17 @@ function internet.request(url, data, headers)
error(reason, 2) error(reason, 2)
end end
return function() return setmetatable(
{
["()"] = "function():string -- Tries to read data from the socket stream and return the read byte array.",
close = setmetatable({},
{
__call = request.close,
__tostring = function() return "function() -- closes the connection" end
})
},
{
__call = function()
while true do while true do
local data, reason = request.read() local data, reason = request.read()
if not data then if not data then
@ -47,7 +57,9 @@ function internet.request(url, data, headers)
-- else: no data, block -- else: no data, block
os.sleep(0) os.sleep(0)
end end
end end,
__index = request,
})
end end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------