From d8471278ba18f5f09e2e8c6cdf494da2b498a02b Mon Sep 17 00:00:00 2001 From: payonel Date: Sat, 4 Feb 2017 14:48:47 -0800 Subject: [PATCH] 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 --- .../loot/openos/lib/internet.lua | 46 ++++++++++++------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/src/main/resources/assets/opencomputers/loot/openos/lib/internet.lua b/src/main/resources/assets/opencomputers/loot/openos/lib/internet.lua index 0b252bb30..c924a0dab 100644 --- a/src/main/resources/assets/opencomputers/loot/openos/lib/internet.lua +++ b/src/main/resources/assets/opencomputers/loot/openos/lib/internet.lua @@ -11,10 +11,10 @@ function internet.request(url, data, headers) checkArg(2, data, "string", "table", "nil") checkArg(3, headers, "table", "nil") - local inet = component.internet - if not inet then + if not component.isAvailable("internet") then error("no primary internet card found", 2) end + local inet = component.internet local post if type(data) == "string" then @@ -31,23 +31,35 @@ function internet.request(url, data, headers) error(reason, 2) end - return function() - while true do - local data, reason = request.read() - if not data then - request.close() - if reason then - error(reason, 2) - else - return nil -- eof + 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 + local data, reason = request.read() + if not data then + request.close() + if reason then + error(reason, 2) + else + return nil -- eof + end + elseif #data > 0 then + return data end - elseif #data > 0 then - return data + -- else: no data, block + os.sleep(0) end - -- else: no data, block - os.sleep(0) - end - end + end, + __index = request, + }) end -------------------------------------------------------------------------------