GMod lua http.fetch返回
我对LUA有一个难题: 我知道http.fetch(url,onsuccess,onfailure)命令。现在我想把这个命令放在一个带返回的函数中GMod lua http.fetch返回,http,lua,add-on,Http,Lua,Add On,我对LUA有一个难题: 我知道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 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)时,它会打印nil,因为http.Fetch函数需要一些时间来获取主体,等等
如何解决这个问题,从而得到“entry”变量
编辑
下面是我调用cl_PPlay.getSoundCloudInfo(rawURL)的代码
它在与的线路上抛出一个错误
PrintTable(e1)
因为e1是零
谢谢解决问题的最简单方法可能是更新函数以获取url和回调,请求成功完成后可以调用该函数。大概是这样的:
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
然后,你可以做一些事情,比如:
cl_PPlay.getSoundCloudInfo('asdfasdf', postProcess)
或
这是一个非常常见的javascript习惯用法,因为您在js中执行的大多数操作都是基于事件的,http请求也不例外。是
http.fetch
还是http.fetch
?返回的是什么?相反,您可以打印字符串”http://api.soundcloud.com/resolve.json?url=“.rawURL..”&client_id=92373aa73cab62ccf53121163bb1246e“
就在调用http.Fetch之前?
cl_PPlay.getSoundCloudInfo('asdfasdf', postProcess)
cl_PPlay.getSoundCloudInfo('asdasdf', function(entry)
-- code to do stuff with entry
end)