function addItemToBag(runtimeScene, eventsFunctionContext, bags, items, bagName, item, infinite, quantity) { // Initialize some variables we'll use later in the function let foundSlot; let foundSlotIndex; let done; // Loop as long as there are items left to add to the bag // or until the loop is explicitly broken by setting `done` to `true` while (quantity > 0 || done == true) { // Make a copy of the bag's slots array and ensure that it has the correct length if (infinite & !bags[bagName]){ bags[bagName] = {}; bags[bagName].slots = [{ name: "0", quantity: 0 }]; bags[bagName].max = 1 } const slots = [...bags[bagName].slots]; slots.length = bags[bagName].max // Find the first slot in the bag that has room for more of the given item // and that already contains at least one of the given item foundSlotIndex = slots.indexOf(slots.find(i => items[item].max - i.quantity > 0 && i.quantity > 0 && i.name === item)); foundSlot = bags[bagName].slots[foundSlotIndex]; // If no such slot was found, find the first empty slot in the bag instead if (foundSlotIndex < 0) { foundSlotIndex = slots.indexOf(slots.find(i => i.quantity == false)) foundSlot = bags[bagName].slots[foundSlotIndex]; } // If a suitable slot was found, add as many items as possible to it if (foundSlotIndex >= 0) { if (items[item].max - foundSlot.quantity >= quantity) { foundSlot.quantity += quantity; quantity = 0; } else { quantity -= items[item].max - foundSlot.quantity; foundSlot.quantity = items[item].max; }; foundSlot.name = item; } // If no suitable slot was found, set a variable with the remaining quantity // and exit the loop by setting `done` to `true` unless it is supposed to be a bag with infinite slots else if (infinite) { const lastMaxSlot = bags[bagName].max; bags[bagName].slots.length += 1; bags[bagName].max += 1; bags[bagName].slots = bags[bagName].slots.fill({ name: "0", quantity: 0 }, lastMaxSlot); } else { return quantity done = true; } } // Update the bags in the game's variables runtimeScene.getGame().getVariables().get("__BetterInventory").getChild("Bags").fromJSObject(bags); } // Get the bags and items from the game's variables let bags = runtimeScene.getGame().getVariables().get("__BetterInventory").toJSObject().Bags; const bagName = eventsFunctionContext.getArgument("bag") const extraBagName = eventsFunctionContext.getArgument("extraBag"); const item = eventsFunctionContext.getArgument("item"); let quantity = eventsFunctionContext.getArgument("quantity") let items = runtimeScene.getGame().getVariables().get("__BetterInventory").toJSObject().Items; // Add the item to the bag, passing in the result of adding the item to the extra bag as the quantity addItemToBag(runtimeScene, eventsFunctionContext, bags, items, extraBagName, item, true, addItemToBag(runtimeScene, eventsFunctionContext, bags, items, bagName, item, false, quantity));