CC:Tweaked与Advanced Peripheral挖矿脚本执行报错求助
Minecraft 1.18.2 挖矿脚本仅处理1个物品就终止的问题修复
你的脚本报错核心原因是部分物品没有tags属性,当代码执行到for _, tag in pairs(item.tags)时,item.tags为nil,而pairs()无法遍历nil值,直接触发参数错误导致脚本停止运行。同时全局作用域的match变量也可能导致逻辑判断混乱。
下面是修复后的完整代码:
--inventory filter, ore dumping for mining --by toastonrye local im = peripheral.find("inventoryManager") local cb = peripheral.find("chatBox") if not im then error("inventoryManager not found") end if not cb then error("chatBox not found") end local filter = false local tagFilter = {"forge:ores", "forge:raw_materials"} local function chatListener() while true do local event = { os.pullEvent("chat") } if event[3]:lower() == "ore on" then filter = true cb.sendMessageToPlayer("ORE ON", event[2]) elseif event[3]:lower() == "ore off" then filter = false cb.sendMessageToPlayer("ORE OFF", event[2]) end end end local function pushItems() while true do if filter then local myInv = im.getItems() -- 改为局部变量,避免全局污染 for slot, item in pairs(myInv) do local match = false -- 将match放到循环内,每次处理新物品时重置 -- 先判断item.tags是否存在,再执行遍历 if item.tags then for _, tag in pairs(item.tags) do for _, v in pairs(tagFilter) do if string.find(tag, v) then match = true break -- 找到匹配标签后跳出内层循环 end end if match then break end -- 已匹配成功,无需遍历剩余标签 end end if match then im.removeItemFromPlayer("UP", item.count, slot) end end end os.sleep(10) end end parallel.waitForAny(chatListener, pushItems)
修复点说明:
- 增加
item.tags存在性判断:只有物品具备标签属性时才执行遍历逻辑,彻底避免nil值报错。 - 调整
match变量作用域:移到物品遍历循环内部,每次处理新物品时自动重置为false,避免旧的匹配结果干扰当前判断。 - 优化循环逻辑:找到匹配标签后立即跳出多层循环,提升脚本运行效率。
- 规范变量声明:将
myInv改为局部变量,符合Lua最佳实践,减少全局变量污染。
内容的提问来源于stack exchange,提问作者xgamerfausn
相关产品推荐
相关产品推荐

