Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local cache = {}
- -- Function that returns a function to cache a single slot of a chest.
- local function cache_item(chest, slot)
- return function()
- -- get detailed info about this one slot
- local detail = chest.getItemDetail(slot)
- -- If there is still an item in that slot (slots can change between calls!)...
- if detail then
- -- cache it.
- cache[detail.name] = detail.displayName
- end
- end
- end
- --- Return a function that goes through a chest and caches all slots.
- --- In total, this method should take two ticks to run, since it's all parallel.
- --- Be careful of large inventory networks! If you have more than 255 inventory slots, this will overflow the event queue and stall the program.
- --- In that case, you may wish to make this function non-parallel.
- local function cache_items(chest)
- return function()
- local funcs = {} -- a list of functions to parallelize
- -- for each slot with an item...
- for slot, item in pairs(chest.list()) do
- -- if we haven't cached this item yet...
- if not cache[item.name] then
- -- Add a caching function to the list of functions we want to run in parallel.
- table.insert(funcs, cache_item(chest, slot))
- end
- end
- -- run all the functions in parallel.
- parallel.waitForAll(table.unpack(funcs))
- end
- end
- -- go through every inventory on the network and cache it, in parallel.
- local function cache_network()
- local inventories = {peripheral.find("inventory")} -- a list of all inventories on the network
- local funcs = {} -- a list of functions to parallelize
- for i, inventory in ipairs(inventories) do
- table.insert(funcs, cache_items(inventory))
- end
- -- run all the functions in parallel
- parallel.waitForAll(table.unpack(funcs))
- end
- -- Then, at the start of your program you can
- cache_network()
- -- Then, whenever you need the displayName of an item, you can use this:
- local display_name = cache[item_name] -- where item_name can be like "minecraft:dirt" or "minecraft:stone"
- -- If the item is not in the cache, you can manually cache it (assuming you have the chest and slot still):
- cache_item(chest, slot)() -- Note the extra parenthesis at the end.
Add Comment
Please, Sign In to add comment