从服务器接收数据时出错

时间:2014-10-03 09:38:56

标签: lua corona

我想让我的测试功能在下面打印出“k不是零”的消息,但我的代码不起作用。它已经从我的服务器收到了k值,但是如果k~ = nil那么它不检查该行。以下是我的代码。感谢任何传入的建议。

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

2 个答案:

答案 0 :(得分:1)

问题是如果第一次尝试没有收到数据,则k为nil,测试返回。在收到数据之前,将以100毫秒的间隔再次调用receiveData,但是performWithDelay会丢弃返回,然后返回test(请参阅此答案的第一句)。

解决方案是设置receiveData在数据最终到达时可以调用的回调。然后回调可以处理数据。将return l,e替换为onReceiveData(l,e),然后在while循环中执行测试等待的操作。当然,receiveData可以通过测试直接设置此标记,但是一旦您的应用变大,最好将接收与流程分开。

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

其中sleep(100)是你能想到的,因为没有内置函数可以在Lua或甚至Corona中执行此操作(尽管Corona的system.getTimer()从应用程序启动后返回ms,所以你可以拥有

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

我不太热衷于空循环,但在测试实用程序函数中它是可以的。如果您正在使用套接字库,它具有休眠功能 - 请查看Lua wiki以获取其他选项。

答案 1 :(得分:0)

您确定收到了数据吗?你的程序在控制台中打印了什么?

您可以考虑以下修改

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

所以我的猜测是,当第二次调用receiveData时,你的返回值(l,e)被丢弃(因为performWithDelay不会对它们做任何事情)。