#Correct way to remove items from a chest

1 messages · Page 1 of 1 (latest)

visual topaz
#

I'm trying to come up with a general function to remove items from a chest given an itemId and a specified amount, but I'm getting some unexpected behavior. When the item stack is about to go from 1 to 0, it throws an "invalid amount" error, saying that the amount has to be greater than 0 and less than 256, which it should be.

This is based off of this (https://discord.com/channels/523663022053392405/1103090654856347749) post, which should be able to do what I'm asking, but I must be missing something.

Here's my code:

function takeItemsFromNearbyChest(block, itemName, amount = 1) {
    const chest = getAdjacentChestsWithItem(block, itemName)[0];

    const inv = chest.getComponent("inventory").container;

    for (let i = inv.size - 1; i >= 0; i--) {
        const item = inv.getItem(i);
        if (item === undefined) continue;
        if (item.typeId != `minecraft:${itemName}`) continue;

        if (item.amount < amount) {
            amount -= item.amount;
            inv.setItem(i);
        } else {
            console.warn(item.amount);
            item.amount -= amount;
            inv.setItem(i, item);
            break;
        }
    }
}
#

I think I figured it out, this seems to work:

function takeItemsFromNearbyChest(block, itemName, amount = 1) {
    const chest = getAdjacentChestsWithItem(block, itemName)[0];

    const inv = chest.getComponent("inventory").container;

    for (let i = inv.size - 1; i >= 0; i--) {
        const item = inv.getItem(i);
        if (item === undefined) continue;
        if (item.typeId != `minecraft:${itemName}`) continue;

        if (item.amount < amount) {
            amount -= item.amount;
            inv.setItem(i);
        } else {
            if (item.amount === amount) {
                inv.setItem(i)
                break
            }

            item.amount -= amount;
            inv.setItem(i, item);

            break;
        }
    }
}