You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenComputers Lua如何为事件等待设置超时?收发脚本卡顿求助

解决Lua Modem脚本卡顿与超时判断问题

你的脚本卡顿是因为event.pull("modem_message")默认会无限阻塞,直到收到对应事件,而且原脚本里的超时实现语法错误、逻辑混乱。下面直接给你修正后的代码,并说明关键修改点:

修正后的代码

local component = require("component")
local event = require("event")
local m = component.modem -- 获取主modem组件
m.open(80)
print(m.isOpen(80)) -- 确认端口已打开

while true do
    -- 获取用户输入,输入为空时退出循环
    local input = io.read()
    if not input then break end
    
    -- 广播消息到80端口
    m.broadcast(80, input)
    
    -- 等待1秒内的回执消息
    -- modem_message事件返回参数:事件名、发送方地址、发送端口、接收端口、距离、消息内容
    local _, _, _, _, _, received_msg = event.pull(1, "modem_message")
    
    -- 判断回执是否匹配
    if received_msg and received_msg == input then
        print("发送成功")
    else
        print("超时或回执不匹配")
    end
end

关键修改说明

  • 直接用event.pull的超时参数:event.pull(1, "modem_message")里的第一个参数1就是超时时间(单位秒),超时后函数会返回nil,不会一直卡住
  • 正确提取回执内容:modem_message事件返回多个参数,第六个才是实际的消息内容,必须正确解构
  • 移除无效的超时逻辑:原脚本里的匿名函数定义语法错误,完全起不到超时作用,直接删掉即可
  • 增加输入退出处理:避免用户输入为空时脚本无意义循环

内容的提问来源于stack exchange,提问作者Wheatley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 20:40:04