Lua编写UDP RS232设备通信代码出现'until' expected near 'elseif'错误求助
问题根源
你的报错是Lua语法结构错误,问题出在if分支的end关键字位置错误:
原代码中if data then分支下多写了一个end,提前闭合了整个if块,导致后续的elseif没有对应的匹配条件,Lua解析器读到elseif时认为当前repeat块应该结束、需要匹配until关键字,因此抛出对应语法错误。
基础修复方案
仅修正语法错误的代码如下:
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) elseif msg ~= 'timeout' then error("Network error: "..tostring(msg)) end until not data
适配UDP串口设备的优化方案
你当前使用0超时的非阻塞模式,原有逻辑会在第一次收不到数据时直接退出循环,大概率会出现设备还没发完全部分段响应就提前终止的问题,建议增加超时判断、拼接完整响应,适配设备特性:
local udp = socket.udp() udp:settimeout(0) udp:setpeername("172.16.0.23", 65432) local cmd = "$RS232 test message\r" udp:send(cmd) local full_resp = "" -- 存储拼接后的完整响应 local last_recv_time = socket.gettime() local idle_timeout = 1.5 -- 空闲1.5秒没收到新包就认为响应结束,可根据实际速率调整 repeat local data, msg = udp:receive() if data then print("received segment:", data) full_resp = full_resp .. data last_recv_time = socket.gettime() elseif msg ~= 'timeout' then error("Network error: "..tostring(msg)) end until (socket.gettime() - last_recv_time > idle_timeout) print("full response:", full_resp)
内容的提问来源于stack exchange,提问作者nodecentral
相关产品推荐
相关产品推荐

