diff --git a/TradeSkillMaster_Mailing/Modules/Inbox.lua b/TradeSkillMaster_Mailing/Modules/Inbox.lua index 08e529b..ea812f1 100644 --- a/TradeSkillMaster_Mailing/Modules/Inbox.lua +++ b/TradeSkillMaster_Mailing/Modules/Inbox.lua @@ -499,6 +499,7 @@ function Inbox:CollectItems(items, callback) local remaining = CopyTable(items) local collected = false + local candidates = {} for i = GetInboxNumItems(), 1, -1 do local _, _, _, _, _, cod, _, hasItem = GetInboxHeaderInfo(i) if hasItem and hasItem > 0 and (not cod or cod == 0) then @@ -508,21 +509,42 @@ function Inbox:CollectItems(items, callback) local need = itemString and remaining[itemString] if need and need > 0 then local quantity = select(3, GetInboxItem(i, j)) or 0 - if quantity > 0 and (quantity <= need or not HasFittableStack(itemString, need)) then - if CanLootItem(itemString, quantity) then - TakeInboxItem(i, j) - remaining[itemString] = max(need - quantity, 0) - collected = true - elseif callback then - callback(L["Cannot finish auto looting, inventory is full or too many unique items."]) - return + if quantity > 0 then + if not candidates[itemString] then + candidates[itemString] = {} end + tinsert(candidates[itemString], { index = i, itemIndex = j, quantity = quantity }) end end end end end + for itemString, entries in pairs(candidates) do + table.sort(entries, function(a, b) + if a.quantity ~= b.quantity then + return a.quantity < b.quantity + end + return a.index > b.index + end) + for _, entry in ipairs(entries) do + local need = remaining[itemString] + if not need or need <= 0 then + break + end + if entry.quantity > 0 and (entry.quantity <= need or not HasFittableStack(itemString, need)) then + if CanLootItem(itemString, entry.quantity) then + TakeInboxItem(entry.index, entry.itemIndex) + remaining[itemString] = max(need - entry.quantity, 0) + collected = true + elseif callback then + callback(L["Cannot finish auto looting, inventory is full or too many unique items."]) + return + end + end + end + end + -- Keep looting as new mail indexes shift, while preserving 1 free slot. if collected then TSMAPI:CreateTimeDelay("craftingGatherMailLoop", 0.4, function()