Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in receiving data from server

Tags:

lua

coronasdk

I want to make my test function below print out the message "k isn't nil" but my code doesn't work. It has already received k value from my server but it doesn't check the line if k~=nil then. Below is my code. Thanks for any incoming advice.

local function receiveData(  )
    local l,e = client:receive()
    if l~=nil then
        print(l)
        return l,e
    else
        timer.performWithDelay(100,receiveData)
    end
end

function test( )
    k = receiveData()
    if k ~=nil then
        print("k isn't nil")
    end
end

test()
like image 541
jade Avatar asked May 19 '26 03:05

jade


1 Answers

The problem is that if the data is not received on the first try then k is nil and test returns. The receiveData will be called again at 100 millisecond intervals until data is received, but the return is discarded by performWithDelay and by then test has returned (see first sentence of this answer).

The solution is to set a callback that receiveData can call when the data eventually arrives. The callback can then process the data. Replace return l,e by onReceiveData(l,e) and have that do something that test waits for in a while loop. Of course receiveData could directly set this flag being watched by test but once your app gets larger it is a good idea to separate receive from process.

function receiveData() 
...
-- then:

local data = nil

function onReceiveData(l,e)
    data = l
    print('ready to process data', data, e)
end

funtion test() 
    receiveData() 
    while data == nil do sleep(100) end 
    print('data received and processed') 
end

test()

where sleep(100) is what you can come up with since there is no builtin function that does that in Lua or even Corona (although Corona has system.getTimer() which returns ms since app start, so you could have

function sleep(ms) 
    local start = system.getTimer() 
    while system.getTimer() - start < ms do 
    end
end

I'm not too keen on the empty while loop but in a test utility function it is OK. If you are using the socket library it has a sleep function -- check out the Lua wiki for other options).

like image 62
Oliver Avatar answered May 22 '26 04:05

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!