// Get variables and arguments let bags = runtimeScene.getGame().getVariables().get("__BetterInventory").toJSObject().Bags; const bagName = eventsFunctionContext.getArgument("bag"); const item = eventsFunctionContext.getArgument("item"); let quantity = eventsFunctionContext.getArgument("quantity"); let items = runtimeScene.getGame().getVariables().get("__BetterInventory").toJSObject().Items; // Keep running until there are no more items to add while (quantity > 0) { // Copy the slots array from the current bag and limit its length to the maximum number of slots const slots = Object.assign([], bags[bagName].slots).length = bags[bagName].max; // Find the first slot that has enough space to add more items and contains the same item, or find the first empty slot let foundSlotIndex = slots.indexOf(slots.find(i => items[item].max - i.quantity > 0 && i.quantity > 0 && i.name === item)) || slots.indexOf(slots.find(i => i.quantity == false)); // If a slot was found, add the items to it if (foundSlotIndex >= 0) { // Get the found slot let foundSlot = bags[bagName].slots[foundSlotIndex]; // If the slot has enough space for all the items, add them all and set the remaining quantity to 0 if (items[item].max - foundSlot.quantity >= quantity) { foundSlot.quantity += quantity; quantity = 0; } // If the slot does not have enough space, add as many items as possible and subtract them from the remaining quantity else { quantity -= items[item].max - foundSlot.quantity; foundSlot.quantity = items[item].max; } // Set the name of the item in the slot foundSlot.name = item; } // If no slot was found, stop adding items and store the remaining quantity in a temporary variable else { runtimeScene.getGame().getVariables().get("__BetterInventory").getChild("temp").getChild("itemNum").setNumber(quantity); quantity = 0; } } // Update the "Bags" variable with the modified slots runtimeScene.getGame().getVariables().get("__BetterInventory").getChild("Bags").fromJSObject(bags);