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

CC: Tweaked中Advanced Peripherals的getItems()函数异常求助

问题解决:Advanced Peripherals Inventory Manager 槽位号获取异常

问题描述

我正在使用Advanced Peripherals的Inventory Manager,想要编写一个将背包物品转移至箱子且保留物品位置的脚本。按照设计,getItems()函数应返回以物品所在槽位号为键、物品数据为值的表,但实际返回的表键是从1开始递增的数字,未记录真实槽位号,与预期不符。

测试代码如下:

local inv = peripheral.find("inventoryManager")
local invTable = inv.getItems()
for slot,item in pairs(invTable) do
    print(slot..": "..item.name.." x"..item.count)
end

解决方案

1. 读取物品对象中的真实槽位属性

Advanced Peripherals的getItems()返回的每个物品对象本身就包含真实槽位号,字段名为slot。你可以修改遍历逻辑,直接读取这个属性来实现按原位置转移:

local inv = peripheral.find("inventoryManager")
local chest = peripheral.find("minecraft:chest") -- 替换为你的箱子外设标识
local invItems = inv.getItems()

for _, item in ipairs(invItems) do
    if item then -- 跳过空槽位
        -- 从背包对应槽位转移到箱子相同编号的槽位
        inv.pushItems(peripheral.getName(chest), item.slot, item.count, item.slot)
        print(string.format("已转移 %s x%d 到槽位 %d", item.name, item.count, item.slot))
    end
end

2. 关于返回结构的说明

你之前对getItems()的返回结构理解有误:它不是以槽位号为键的字典,而是一个按物品存在顺序排列的数组(键从1开始递增),但数组内的每个物品对象都携带了slot字段,存储该物品所在的真实槽位编号。

3. 遍历全槽位的替代方案

如果需要处理所有槽位(包括空槽位),可以先通过getSize()获取总槽位数,再逐个检查并转移:

local inv = peripheral.find("inventoryManager")
local chest = peripheral.find("minecraft:chest")
local totalSlots = inv.getSize()

for slot = 1, totalSlots do
    local item = inv.getItem(slot)
    if item then
        inv.pushItems(peripheral.getName(chest), slot, item.count, slot)
    end
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:30:42