Domanda

I have a difficult problem with LUA here: I know the http.fetch(url, onsuccess, onfailure) command. And now I want to put this command in a function with a return.

function cl_PPlay.getSoundCloudInfo( rawURL )

local entry


http.Fetch( "http://api.soundcloud.com/resolve.json?url="..rawURL.."&client_id=92373aa73cab62ccf53121163bb1246e",
    function( body, len, headers, code )
        entry = util.JSONToTable( body )
        if !entry.streamable then
            cl_PPlay.showNotify( "SoundCloud URL not streamable", "error", 10)
        end
    end,
    function( error )
        print("ERROR with fetching!")
    end
);

return entry

end

So this code seems fine, but when I call cl_PPlay.getSoundCloudInfo(SOMEURL) it prints nil, because the http.Fetch function needs some time to get the body and so on.

How do I solve the problem, so that I get the "entry" variable??

EDIT

Here is the code, in which I call cl_PPlay.getSoundCloudInfo( rawURL )

local e1 = cl_PPlay.getSoundCloudInfo(te_url:GetValue())
    PrintTable(e1)

it throws an error on the line with

PrintTable(e1)

because e1 is nil

Thank you

È stato utile?

Soluzione

probably the easiest way to fix your problem is to update your function to take both a url and a callback that it can invoke after the request has been successfully completed. something like this:

function postProcess(entry)
  -- do something with entry
end

function cl_PPlay.getSoundCloudInfo(rawURL, cb)
    local entry

    local url = "http://api.soundcloud.com/resolve.json?url="..rawURL.."&client_id=92373aa73cab62ccf53121163bb1246e"
    http.Fetch(url,
      function(body, len, headers, code)
          entry = util.JSONToTable(body)
          if !entry.streamable then
              cl_PPlay.showNotify( "SoundCloud URL not streamable", "error", 10)
              return
          end
          -- here we know entry is good, so invoke our post process function and
          -- give it the data we've fetched
          cb(entry);
      end,
      function( error )
          print("ERROR with fetching!")
      end
    );
end

then, you can do stuff like:

cl_PPlay.getSoundCloudInfo('asdfasdf', postProcess)

or

cl_PPlay.getSoundCloudInfo('asdasdf', function(entry) 
    -- code to do stuff with entry
end)

this is a pretty common javascript idiom since most of what you do in js is event based, http requests are no different.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top