Seeker14491

gather_mats

Jun 20th, 2022 (edited)
719
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.03 KB | None | 0 0
  1. -- Moves items from SRC to DEST as specified by INPUT_FILE, which is a JSON
  2. -- file in the format obtained by using the copy button of St'ructure Tools'
  3. -- Copy Paste Gadget
  4.  
  5. local SRC = "left"
  6. local DEST = "right"
  7. local INPUT_FILE = "input.json"
  8.  
  9. local src = peripheral.wrap(SRC)
  10. local dest = peripheral.wrap(DEST)
  11.  
  12. local function clear_dest()
  13.   for slot, item in pairs(dest.list()) do
  14.     local pushCount = dest.pushItems(SRC, slot)
  15.     if pushCount < item.count then
  16.       print("Not enough room in SRC to clear DEST into")
  17.       error()
  18.     end
  19.   end
  20. end
  21.  
  22. local needed = {}
  23. do
  24.   local success, input = pcall(function()
  25.     io.input(INPUT_FILE)
  26.     return textutils.unserializeJSON(io.read("*a")).header.material_list.root_entry
  27.   end)
  28.   if not success then
  29.     print("Error deserializing JSON")
  30.     error()
  31.   end
  32.   for _, v in pairs(input) do
  33.     needed[v.item.item] = v.count
  34.   end
  35. end
  36.  
  37. clear_dest()
  38.  
  39. local srcMats = {}
  40. do
  41.   for slot, item in pairs(src.list()) do
  42.     srcMats[item.name] = srcMats[item.name] or {slots = {}, total = 0}
  43.     local t = srcMats[item.name]
  44.     t.slots[#t.slots + 1] = slot
  45.     t.total = t.total + item.count
  46.   end
  47. end
  48.  
  49. local errored = false
  50.  
  51. -- Move mats to dest
  52. for item, neededCount in pairs(needed) do
  53.   local stillNeeded = neededCount
  54.   local t = srcMats[item] or {slots = {}, total = 0}
  55.   for _, slot in ipairs(t.slots) do
  56.     stillNeeded = stillNeeded - dest.pullItems(SRC, slot, neededCount)
  57.     if stillNeeded <= 0 then
  58.       break
  59.     end
  60.   end
  61.  
  62.   if stillNeeded > 0 then
  63.     print("Missing " .. stillNeeded .. "/" .. neededCount .. " " .. item)
  64.     errored = true
  65.   end
  66. end
  67.  
  68. if errored then
  69.   -- Detect the possibility that dest is not big enough
  70.   local filled_dest_slots = 0
  71.   for _ in pairs(dest.list()) do
  72.     filled_dest_slots = filled_dest_slots + 1
  73.   end
  74.   if filled_dest_slots >= dest.size() then
  75.     print("Warning: previous errors may be due to destination storage not being big enough")
  76.   end
  77.  
  78.   clear_dest()
  79.   error()
  80. end
  81.  
  82. print("Success")
Add Comment
Please, Sign In to add comment