diff --git a/QuickStackToBag/Lua/Autorun/init.lua b/QuickStackToBag/Lua/Autorun/init.lua index 7828ea2..cd816ea 100644 --- a/QuickStackToBag/Lua/Autorun/init.lua +++ b/QuickStackToBag/Lua/Autorun/init.lua @@ -415,6 +415,24 @@ local function buildItemTree(inventory, itemTree, iter) return itemTree end +---@param slot Barotrauma.ItemInventory.Slot +---@param itemLocation ItemLocation +local function moveItemsTo(slot, itemLocation) + local totalHere = #slot.items + local moveHere = math.min(itemLocation.maxFits, totalHere) + debugPrint("Attempting to move " .. + moveHere .. " items to inventory at slot index: " .. itemLocation.slotIndex) + if moveHere > 0 then + for _, item in ipairs(slot.items) do + itemLocation.inventory.TryPutItem(item, itemLocation.slotIndex, false, true, nil) + itemLocation.maxFits = itemLocation.inventory.HowManyCanBePut(item.Prefab, itemLocation.slotIndex) + if itemLocation.maxFits <= 0 then + return + end + end + end +end + local function stackInventoryItems(inventory, itemTree) debugPrint("Starting to stack inventory items...") for slotIndex, slot in ipairs(inventory.slots) do @@ -428,28 +446,11 @@ local function stackInventoryItems(inventory, itemTree) debugPrint("Items to move: " .. toMove) ---@type ItemLocation[] local locations = itemTree[identifier] - if locations then - debugPrint("Found locations for identifier: " .. identifier) - for _, location in ipairs(locations) do - local moveHere = math.min(location.maxFits, toMove) - debugPrint("Attempting to move " .. - moveHere .. " items to inventory at slot index: " .. location.slotIndex) - if moveHere > 0 then - for _, itemToMove in ipairs(slot.items) do - location.inventory.TryPutItem(itemToMove, location.slotIndex, false, true, nil) - toMove = toMove - 1 - location.maxFits = location.maxFits - 1 - if location.maxFits <= 0 then location.maxFits = 0 end - if toMove <= 0 then break end - end - debugPrint("Moved " .. moveHere .. " items. Remaining to move: " .. toMove) - else - debugPrint("No items to move for this location.") - end - end - else - debugPrint("No locations found for identifier: " .. identifier) + for _, location in ipairs(locations) do + moveItemsTo(slot, location) end + -- If we have processed all the locations and we still have items to move + -- Then put them into the empty slots: else debugPrint("Slot index " .. slotIndex .. " is empty.") end