Error retrieving data from server

I want to do my test function below, print the message "k is not nil", but my code is not working. It already got the value k from my server, but it doesn't check the string if k ~ = nil then. Below is my code. Thanks for any advice coming in.

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()

      

+3


source to share


2 answers


The problem is that if no data is received on the first try, then k is zero and the test returns. receiveData

will be called again at 100 millisecond intervals until data is received, but the return will be discarded by performWithDelay and returned by that time test

(see the first sentence of this answer).

The solution is to set up a callback that receiveData

can be called when the data eventually arrives. The callback can handle the data. Replace return l,e

with onReceiveData(l,e)

and try to do something that is waiting for the test in a loop while

. Of course, it receiveData

can directly set this flag under the supervision of the test, but once your application gets bigger, it's a good idea to separate the reception from the 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 think of, as there is no built-in function that does this in Lua or even Corona (although Corona has system.getTimer()

that which returns ms from when the application was started, so you can have

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

      

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

+1


source


Are you sure you received the data? What does your program print to the console?

You can consider the following modification



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

      

So my guess is that when getData gets called a second time, your return values ​​(l, e) are discarded (since performWithDelay doesn't do anything with them). In the meantime, there is no need to worry about it.

0


source







All Articles