I would like to solve a problem of conditional looping and random selection in Lua. In the code below, "value.original.source" can be empty (nil) in a record, so I would like to keep fetching records, while it is empty. Then, I need to randomly select one record out of the fetched records (which has "value.original.source"). In the end, the data in the record should be available as variables across different files (global variables?). I try "while...do", "repeat...until" and math.random, but it is tricky and challenging.
Any ideas and solutions are highly appreciated. Thank you!
--Create empty tables
t = {}
t2 = {}
-- 1st API call
local json = require( "json" )
local function getWikipediaData( event )
local res = json.prettify( event.response )
local decoded = json.decode( res )
for key, value in pairs(decoded.results.bindings) do
local pname = value.person_name.value
local dbpuri = value.person.value
-- Put data into a table
t["PNAME"] = pname
t["DBPURI"] = dbpuri
-- Print key-value
for key,value in pairs(t) do
print(key,value)
end
local wikititle = string.gsub(dbpuri, "http://ift.tt/177k8UM", "")
print (wikititle)
-- 2nd API call in which a function is nested
network.request(
"http://ift.tt/2wqDhWw"..wikititle,"GET",
function(event)
local res2 = json.prettify( event.response )
local decoded2 = json.decode( res2 )
-- This part is the tricky part I have problems. "value.original.source" can be empty (nil) in a record, so I would like to keep fetching records, while it is empty. Then, among the fetched records (with value.original.source in them), finally I would like to select one record randomly. The data in the record (in a variable) should be passed to other files.
while (pickdata == nil) do
-- Next level to "pages" is array, so for is used to repeat fetching data
for key, value in pairs(decoded2.query.pages) do
-- Put data into a table
local source = value.original.source
table.insert(t2, source)
end
end
end,params)
end
end
-- This is the second task to try to randomnly select a record with an image from the table created, but does not work. Looping and local vs global variables are the issues to be resolved.
local pick = math.random(3)
local pickdata = t2[pick]
print (pickdata)
local headers = {}
headers["Content-Type"] = "application/json"
local body = ""
local params = {}
params.headers = headers
params.body = body
network.request("http://ift.tt/2xkVOQC(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)
Aucun commentaire:
Enregistrer un commentaire