http.request and function question.

I could have sworn I had this figured out but it seems I do not. I’m trying to create a function that handles http.requests. You pass a url such as img = getFile(“url here”). However the http.request() moves on before the success callback function thus img will be = to nil. Is there any way to pass a reference to a funcion so the function could edit the reference? such as:

local img = nil
img = hlib.getFile("url here",img)
--img stays nill do to the function finishing before the callback

hlib.getFile = function(file,ret)
    
    function didGetData(data,status,head)
    print(status)
--any way to use ret as a pointer to img so I can set img here?
        ret = data
        
        print("File Request Sucess!")
        
    end
    
    http.request(file,didGetData)
    
    return ret
end

I hope I’m being clear enough. Basically hlib.getFile is being imported into projects. I use it to get multiple http requests so i cant have a set variable to hold the returned data. if http.request would wait for the callback to finish it would be easy to just use return.

Looks like you want to use a pointer to a pointer, but no such thing exists in Lua. Either you need to have the variable img visible for the callback function, or create another object to return.

I’ve solved something similar like this: the function readRemoteImage returns an image object than then the resulting image is rendered into.


--# ReadRemoteImage
local imageMap = {
    ["Documents:GreyButton"] = {128,128,
        "https://dl.dropbox.com/s/97ru3ti7zvwa9eu/Photo%202013-02-23%2021%2031%2037.png"
    },
    ["Documents:Earth"] = {2048,1024,
        "https://dl.dropbox.com/s/fzrsg4mzzchm325/earth.jpg"
    }
}
function readRemoteImage(name)
    if type(name) == "string" then
        local img = readImage(name)
        if img == nil then
            local data = imageMap[name]
            if type(data) == "userdata" then
                return data
            end
            local w,h,url = unpack(data or {1,1})
            img = image(w,h)
            imageMap[name] = img
            if url then
                http.request(url, function (data)
                    pushStyle()
                    setContext(img)
                    spriteMode(CORNER)
                    sprite(data,0,0,w,h)
                    setContext()
                    popStyle()
                    saveImage(name, data)
                end)
            end
        end
        return img
    else
        return name
    end
end