You need to enable JavaScript to run this app. ComputerCraft开发Lua聊天程序时sender为nil报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

ComputerCraft开发Lua聊天程序时sender为nil报错如何解决

错误原因与解决方案

你遇到的报错是chatreceive.lua:3: attempt to concatenate global 'sender' (a nil value),根因为rednet.receive()调用后未返回有效的发送方ID,导致sender变量为空值,字符串拼接操作失败。

可按以下步骤排查修复:

  • 确认外设连接配置:检查运行脚本的计算机右侧是否安装了正常可用的调制解调器,且未被红石信号禁用。如果调制解调器安装在其他方位,需要将rednet.open("right")中的参数修改为对应方位(可选值为left/right/top/bottom/front/back)。
  • 新增调制解调器打开校验逻辑,避免打开失败后继续执行无效逻辑,参考代码:
-- 尝试打开右侧调制解调器,捕获打开结果
local openResult = rednet.open("right")
if not openResult then
    print("调制解调器打开失败,请检查外设配置")
    return
end
  • 新增接收结果的空值判断,避免无效消息触发报错,参考完整可运行代码:
local openResult = rednet.open("right")
if not openResult then
    print("调制解调器打开失败")
    return
end

-- 循环监听消息,可按Ctrl+T终止脚本
while true do
    local sender, message = rednet.receive()
    -- 仅在收到有效消息时打印内容
    if sender and message then
        print("computer " .. sender .. " has sent :")
        print(message)
    end
end
  • 测试时请确认发送端也已正常开启对应调制解调器,可先使用rednet.broadcast("测试消息")广播消息验证接收端是否正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:15:03