PutItemInBag wants an InventorySlotId, not a slot in a bag. 20, 21, 22, and 23 are the bag slots. You should also break out of the inner loops once you put the item in a bag.
Lua Code:
local ignore,foundspot={[0]={},[1]={},[2]={},[3]={},[4]={},}
for k, v in pairs(EquipmentSlots) do
PickupInventoryItem(v)
foundspot = false
if CursorHasItem() then
for bag = 4, 0, -1 do
for slot = 1, GetContainerNumSlots(bag) do
if not ignore[bag][slot] and not GetContainerItemID(bag, slot) then
if bag == 0 then
PutItemInBackpack()
else
PutItemInBag(bag+19)
end
ignore[bag][slot] = true
foundspot = true
break
end
end
if foundspot then
break
end
end
end
end
Edit: Fizzlemizz makes a good point. Based on your wording, it does look like you would rather fill other bags with the unequipped gear before your backpack. I reversed the bag loop so your backpack is searched last.
Edit2: Added CursorHasItem and an ignore table to keep track of spots filled by the code.