luvit / lit

Toolkit for developing, sharing, and running luvit/lua programs and libraries.
http://lit.luvit.io/
Apache License 2.0
245 stars 58 forks source link

Coro-Http returning nil #239

Closed OliverHensworth closed 6 years ago

OliverHensworth commented 6 years ago

its all in the title,

local function request(link)
    coroutine.wrap(function()
        local res, id = http.request("GET", link)

        print(id)
        return id
    end)
end

request("https://www.google.com/") --just put google because i dont wanna say the website name

is returning nil

JohnnyMorganz commented 6 years ago

coroutine.wrap returns a function, which you must later run You forgot to call said function, so it must be something like this:

return coroutine.wrap(func)()

So, In your code

return coroutine.wrap(function()
    local res, id = http.request("GET", link)
    print(id)
    return id
end)()

that should work

OliverHensworth commented 6 years ago

that just returns a function value; attempt to index local 'info' (a function value)

even tho my code is

function request(link)
    return coroutine.wrap(function()
        local res, id = http.request("GET", link)

        return id
    end)    ()
end
squeek502 commented 6 years ago

You need coroutine.wrap to be outside of the request function. Right now, request is returning before the coroutine has finished running, so you aren't getting the results. You can see this by running the following code:

local function request(link)
    local res, body = coroutine.wrap(function()
        print("coroutine started")
        local res, body = http.request("GET", link)
        print("http.request finished")
        return res, body
    end)()
    print("returning:", tostring(res), tostring(body))
    return res, body
end

request("https://www.google.com/")

which will output

coroutine started
returning:      nil     nil
http.request finished

This should work, though:

local function request(link)
    return http.request("GET", link)
end

coroutine.wrap(function()
    local res, body = request("https://www.google.com/")
    print("Response is " .. #body .. " bytes long, status: " .. res.code)
end)()