I'm new to Corona SDK and Lua language and I have some troubles..
so I have this function which sends network request to my site and through json I receive the data. This works great.
The problem is that when I call the variable with the data response outside the listener function, it seems to be nil
. I put a small timer to track if the issue was because of the time between the request and response and it seems to be that one (but I'm not sure 100%). I don't want to use custom delay to perform this operation.
Is there some way to pause the script until the listener response and then continue execution? I have tried with coroutines but I couldn't solve it..
local data
function networkListener( event )
if ( event.isError ) then
print( "Network error!")
else
--print ( "RESPONSE: " .. event.response )
data = json.decode(event.response)
print( data[1].start_date ) --working great
end -- end of else statement
end
network.request( "http://localhost/mysite/myphpmethod" , "GET", networkListener )
print(data) -- error: attempt to index upvalue 'data' ( a nil value )
local function printIt()
print( data[1].start_date)
end
timer.performWithDelay(1000, printIt, 1); -- this works
The HTTP call is asynchronous, which means indeed that your print(data) will almost always be empty, even the performWithDelay might be empty on a bad day.
You will have to design your app in such a way that the game code continues within networkListener() ( in this particular case you would call printIt() from networkListener().
This takes some thinking and re-designing but it is not that bad.