0
votes

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 
3

3 Answers

1
votes

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.

0
votes

You can also call native.setActivityIndicator(true) while sending request to the server and stop the indicator(native.setActivityIndicator(false)) in event.response. So when you get the response from server, you can do your stuff.

0
votes

Th easiest way is to do the request and pop up a new button that then does whatever you need to do with the data, many good websites do that. You can also use the event.phase == "ended" but not sure how good it works.