Advertisement
Shaka01

mainPC showTopItems

Jan 31st, 2023
768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.86 KB | None | 0 0
  1. maxItems = 15 --number of items to show
  2.  
  3. -- define an array of colors
  4. local colors = {1, 32}
  5.  
  6. -- wrap around the monitor
  7. local side = "top" ---monitor
  8. local inv = peripheral.wrap("right")
  9. local wrap = peripheral.wrap(side)
  10. local currCol = 1
  11. if wrap == nil then
  12.   print("No peripherals on side: " .. side)
  13.   return
  14. end
  15.  
  16. -- set the background color
  17. local bgColor = 32768
  18. wrap.setBackgroundColor(bgColor)
  19.  
  20. -- scan the inventory using inventory.list()
  21. tInventory = inv.list()
  22. if tInventory == nil then
  23.   print("Unable to access inventory")
  24.   return
  25. end
  26.  
  27. -- create a table to store the item counts
  28. local tCounts = {}
  29. for i,v in pairs(tInventory) do
  30.   -- extract the item name from v.name
  31.   local sName = string.match(v.name, ": *(.*)")
  32.   if sName == nil then
  33.     sName = v.name
  34.   end
  35.   -- replace any _ characters with spaces
  36.   sName = string.gsub(sName, "_", " ")
  37.   if tCounts[sName] == nil then
  38.     tCounts[sName] = v.count
  39.   else
  40.     tCounts[sName] = tCounts[sName] + v.count
  41.   end
  42. end
  43.  
  44. -- sort the counts in descending order
  45. local tSorted = {}
  46. for k,v in pairs(tCounts) do
  47.   table.insert(tSorted, {name=k, count=v})
  48. end
  49. table.sort(tSorted, function(a,b) return a.count > b.count end)
  50.  
  51. -- display the top 10 items on the monitor
  52. wrap.setTextScale(0.5) -- set the text scale to 1
  53. wrap.clear() -- clear the monitor
  54. wrap.setCursorPos(1,1) -- set the cursor position to (1,1)
  55. wrap.setTextColor(2048)
  56. wrap.write("Top ".. maxItems.." items in storage:\n")
  57. for i=1,maxItems do
  58.   if tSorted[i] ~= nil then
  59.     wrap.setCursorPos(1,i+2) -- set the cursor position to (1,i+1)
  60.     if currCol == 2 then
  61.         currCol = 1
  62.     elseif currCol == 1 then
  63.         currCol = 2
  64.     end
  65.     wrap.setTextColor(colors[currCol]) -- set the text color
  66.     wrap.write(tSorted[i].name .. ": " .. tSorted[i].count)
  67.   end
  68. end
  69. local event, side, x, y = os.pullEvent("monitor_touch")
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement