如何在调用闭包之前创建一个Lua函数块

时间:2014-10-22 17:01:18

标签: lua coroutine

我有一个定制的Lua解释器可执行文件,内置了一些基本的套接字功能。它不是Luasocket,而且我想在这里使用Luasocket,我不能(所以请不要&# 39;建议将其作为答案)。

我正在使用的套接字API依赖于异步闭包来表示网络操作已完成。因此,在下面的代码中,socketConnect()会立即返回,然后在连接完成后稍后调用onConnect()

local function onConnect(cookie, err, sock)
  print("Connected!")
end

local function connect(host, port)
  local success, err = socketConnect(host, port, onConnect)
  print("Connecting...")
end

所以,这就是问题所在。我想创建connect()功能块,直到调用onConnect()闭包。我在Lua很新,但我希望协程在这里有用吗?

编辑:这是我尝试使用协程制作功能块:

local connected = false
local function onConnect(cookie, err, sock)
  print("Connected!")
  connected = true
end

local coroConnect = coroutine.create(
  function()
    local success, err = socketConnect(m_sHost, m_nPort, onConnect);
    while not connected do
      coroutine.yield()
    end
  end
)

local function connect(sHost, nPort)
  m_sHost = sHost
  m_nPort = nPort
  while not coroutine.status(coroConnect) ~= "dead" do
    coroutine.resume(coroConnect)
    print("Connecting...")
  end
end

1 个答案:

答案 0 :(得分:1)

如果您想使用协同程序,那么这些内容可能对您有用(或者让您知道要尝试的内容):

-- this should really be a socket property, but good enough for this example
local connected
local function onConnect(cookie, err, sock)
  print("Connected!")
  connected = true
end

local function connect(host, port)
  connected = false
  local success, err = socketConnect(host, port, onConnect)
  while not connected do
    coroutine.yield()
  end
  print("Connecting...")
end

如果你现在从connect函数创建一个协同程序并继续使用coroutine.resume调用该协程,直到它完成(coroutine.status该协程将返回' dead& #39;),您将获得所需的结果。显然,您可以将while循环移动到socketConnect函数本身,这将使得从用户角度来看是同步的,因为在onConnect执行之前它不会返回任何内容。