GMod lua http.fetch 返回值。

我在 LUT 中遇到了一个困难的问题: 我知道 http.fetch(url, onsuccess, onfailure) 命令。现在我想将此命令放在一个带有返回的函数中。

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

所以这段代码似乎没问题,但当我调用cl_PPlay.getSoundCloudInfo(SOMEURL)时,它打印为空,因为 http.Fetch 函数需要一些时间来获取正文等信息。

我该怎么解决这个问题,以便我能够得到“entry”变量?

编辑

这是代码,其中我调用cl_PPlay.getSoundCloudInfo(rawURL)

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

它在此行上引发错误

PrintTable(e1)

因为e1为空

谢谢。

点赞
用户1208078
用户1208078

可能解决你的问题最简单的方法是更新你的函数,使其可以接受一个URL和一个回调函数,在请求成功完成后调用它。像这样:

function postProcess(entry)
  -- 对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
          -- 在这里我们知道entry是好的,所以调用我们的后处理函数,
          -- 并将获取的数据传递给它
          cb(entry);
      end,
      function( error )
          print("ERROR with fetching!")
      end
    );
end

然后,你可以做这样的事情:

cl_PPlay.getSoundCloudInfo('asdfasdf', postProcess)

或者

cl_PPlay.getSoundCloudInfo('asdasdf', function(entry)
    -- 处理entry的代码
end)

这是一个非常常见的javascript习惯用语,因为大部分javascript都是基于事件的,HTTP请求也不例外。

2014-04-21 16:51:04