【发布时间】:2017-08-17 15:45:09
【问题描述】:
在一个 Lua 文件中,我想同时调用两个 API 并从两个 API 中获取数据。到目前为止,我设法调用了一个 API 并打印了一个数据,但是不确定如何使用从第一个 API 调用中获得的字符串来调用第二个调用。
local json = require( "json" )
local function networkListener( event )
local res = json.prettify( event.response )
local decoded = json.decode( res )
if ( event.isError ) then
print( "--Network error-- ", ( res ) )
else
print( "Data: " .. ( res ) )
print(decoded.results.bindings[1].person.value)
print(decoded.results.bindings[1].type.value)
local dbpuri = decoded.results.bindings[1].person.value
local wikititle = string.gsub(dbpuri, "http://dbpedia.org/resource/", "")
print (wikititle)
end
end
local headers = {}
headers["Content-Type"] = "application/json"
local body = ""
local params = {}
params.headers = headers
params.body = body
network.request("https://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=select+*%0D%0Awhere+{%3Fperson+rdfs%3Alabel+%3Fperson_name+%3B+rdf%3Atype+%3Ftype+%3B+dbo%3AbirthDate+%3Fbirthdate+.%0D%0A++++bind(rand(1+%2B+strlen(str(%3Fperson))*0)+as+%3Frid)%0D%0AFILTER+regex(%3Ftype%2C+%22Person%22)%0D%0A}+order+by+%3Frid%0D%0ALIMIT+10&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&debug=on&format=json", "GET", networkListener, params)
这是第一次 API 调用(成功),但我想传递局部变量“wikititle”来调用第二次 API 调用。我在前面的代码下方添加了一个几乎相同的代码(见下文),但它得到一个错误:“尝试连接本地'wikititle'(一个零值)......”
local json = require( "json" )
local function networkListener( event )
local res = json.prettify( event.response )
local decoded = json.decode( res )
if ( event.isError ) then
print( "--Network error-- ", ( res ) )
else
print( "Data: " .. ( res ) )
print(decoded.query.pages.original.source)
print(decoded.warnings.pageimages)
end
end
local headers = {}
headers["Content-Type"] = "application/json"
local body = ""
local params = {}
params.headers = headers
params.body = body
network.request("https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles="..wikititle.."", params)
我是 Lua 的初学者,但谁能帮我找到一个好的解决方案? (我想我应该使用前向声明,最好避免重复代码中的两个 API 调用)。非常感谢!
【问题讨论】: