Advertisement
Alexr360

Sort

Feb 19th, 2024 (edited)
975
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.71 KB | None | 0 0
  1. -- Function to count the total number of items in the chest
  2. local function countItems(chest)
  3.     local itemCount = {}
  4.     for slot = 1, chest.size() do
  5.         local stack = chest.getItemDetail(slot)
  6.         if stack then
  7.             local itemName = stack.name
  8.             itemCount[itemName] = (itemCount[itemName] or 0) + stack.count
  9.         end
  10.     end
  11.     return itemCount
  12. end
  13.  
  14. -- Function to compare two item counts
  15. local function compareItemCount(itemCount1, itemCount2)
  16.     for itemName, count in pairs(itemCount1) do
  17.         if itemCount2[itemName] and itemCount2[itemName] > count then
  18.             return true -- itemCount2 has more of this item
  19.         end
  20.     end
  21.     return false
  22. end
  23.  
  24. -- Function to move items from one slot to another within the same chest
  25. local function moveItems(chest, slot1, slot2)
  26.     chest.pushItems(peripheral.getName(chest), slot1, 1, slot2)
  27. end
  28.  
  29. -- Function to sort the items in the chest
  30. local function sortChest(chest)
  31.     local sorted = false
  32.     while not sorted do
  33.         sorted = true
  34.         for slot = 1, chest.size() - 1 do
  35.             local stack1 = chest.getItemDetail(slot)
  36.             local stack2 = chest.getItemDetail(slot + 1)
  37.             if stack1 and stack2 and compareItemCount({[stack1.name] = stack1.count}, {[stack2.name] = stack2.count}) then
  38.                 moveItems(chest, slot, slot + 1)
  39.                 sorted = false
  40.             end
  41.         end
  42.     end
  43. end
  44.  
  45. -- Main function
  46. local function main()
  47.     local chest = peripheral.find("minecraft:chest")
  48.     if chest then
  49.         sortChest(chest)
  50.         print("Chest sorted successfully!")
  51.     else
  52.         print("No chest detected.")
  53.     end
  54. end
  55.  
  56. -- Call the main function
  57. main()
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement