Lua : 'until' expected (to close 'repeat' at line 7) near 'elseif'

我试图编写一些 Lua 代码,发送一个命令,然后捕获来自 UDP 设备的所有分段响应。

以下是我的目前代码

local udp = socket.udp()
udp:settimeout(0)
udp:setpeername("172.16.0.23", 65432)
local cmd = "$RS232 test message\r"
udp:send(cmd)

repeat
    local data, msg = udp:receive()
    if data then
        print("received:", data)
        end
    elseif msg ~= 'timeout' then
        error("Network error: "..tostring(msg))
    end
until not data

但它一直给我以下错误..

代码错误:第12行:期望 'until'(在第7行关闭 'repeat')附近 'elseif'

有什么想法我错过了什么吗?

关于我连接的 udp(串行 rs232)设备的快速背景,数据被发送为许多两个或三个字节的数据包。这是因为 RS232 数据速率和设备使用中断处理数据。基本上,UDP 设备接收几个字节,中断触发,然后它处理那些然后再接收几个中断再次触发,等等等等。

因此,上面的重复循环是为了确保我已经捕获了它为我提供的所有内容?

原文链接 https://stackoverflow.com/questions/69159266

点赞
stackoverflow用户2858170
stackoverflow用户2858170

你的 if 语句被过早结束了。

if data then
    print("received:", data)
end                      -- remove this end!
elseif msg ~= 'timeout' then
    error("Network error: "..tostring(msg))
end

我认为那个 repeat 语句没有太多意义。为什么不用超时呢?

如果你移除了那个 end,你将会接收一次超时为 0 的数据。因为你的对等端从未有机会返回数据,所以 data 将会是 nil,你的循环将会终止。

也许你应该再读一遍文档。

此外,我不理解你如何将 udp 和 rs232 相关联。这是两个完全不同的东西。

2021-09-13 08:30:00