fatboychummy

Caching Basics with Parallel

Mar 5th, 2024 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.19 KB | None | 0 0
  1. local cache = {}
  2.  
  3. -- Function that returns a function to cache a single slot of a chest.
  4. local function cache_item(chest, slot)
  5.   return function()
  6.     -- get detailed info about this one slot
  7.     local detail = chest.getItemDetail(slot)
  8.  
  9.     -- If there is still an item in that slot (slots can change between calls!)...
  10.     if detail then
  11.       -- cache it.
  12.       cache[detail.name] = detail.displayName
  13.     end
  14.   end
  15. end
  16.  
  17. --- Return a function that goes through a chest and caches all slots.
  18. --- In total, this method should take two ticks to run, since it's all parallel.
  19. --- Be careful of large inventory networks! If you have more than 255 inventory slots, this will overflow the event queue and stall the program.
  20. --- In that case, you may wish to make this function non-parallel.
  21. local function cache_items(chest)
  22.   return function()
  23.     local funcs = {} -- a list of functions to parallelize
  24.  
  25.     -- for each slot with an item...
  26.     for slot, item in pairs(chest.list()) do
  27.       -- if we haven't cached this item yet...
  28.       if not cache[item.name] then
  29.         -- Add a caching function to the list of functions we want to run in parallel.
  30.         table.insert(funcs, cache_item(chest, slot))
  31.       end
  32.     end
  33.  
  34.     -- run all the functions in parallel.
  35.     parallel.waitForAll(table.unpack(funcs))
  36.   end
  37. end
  38.  
  39. -- go through every inventory on the network and cache it, in parallel.
  40. local function cache_network()
  41.   local inventories = {peripheral.find("inventory")} -- a list of all inventories on the network
  42.   local funcs = {} -- a list of functions to parallelize
  43.  
  44.   for i, inventory in ipairs(inventories) do
  45.     table.insert(funcs, cache_items(inventory))
  46.   end
  47.  
  48.   -- run all the functions in parallel
  49.   parallel.waitForAll(table.unpack(funcs))
  50. end
  51.  
  52. -- Then, at the start of your program you can
  53. cache_network()
  54.  
  55. -- Then, whenever you need the displayName of an item, you can use this:
  56. local display_name = cache[item_name] -- where item_name can be like "minecraft:dirt" or "minecraft:stone"
  57.  
  58. -- If the item is not in the cache, you can manually cache it (assuming you have the chest and slot still):
  59. cache_item(chest, slot)() -- Note the extra parenthesis at the end.
Add Comment
Please, Sign In to add comment