From 3e693c27567934aebf625c000d79c4e678a9fae7 Mon Sep 17 00:00:00 2001 From: D4VID Date: Sat, 30 Nov 2024 20:57:03 +0100 Subject: [PATCH] Big speedup Using a single call to get an iterator using getAllStacks instead of doing a call for each slot individually --- craft.lua | 40 +++++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/craft.lua b/craft.lua index a4a733c..c6f16bb 100644 --- a/craft.lua +++ b/craft.lua @@ -85,17 +85,21 @@ end ---@return table|nil local function read_chest_contents() local contents = {} - local size = inventory.getInventorySize(sides.forward) - if not size then - return nil + + local iter = inventory.getAllStacks(sides.forward) + if not iter then + return nil -- not facing an inventory end - for slot = 1, size do - local stack = inventory.getStackInSlot(sides.forward, slot) - if stack then + + local stack = iter() + while stack do + if stack.name then -- check if the slot has an item in it local name = stack.name .. ";" .. stack.damage add(contents, name, stack.size) end + stack = iter() end + return contents end @@ -105,11 +109,12 @@ local function store_item() -- check if that item is present in the inventory local item = inventory.getStackInInternalSlot() - local size = inventory.getInventorySize(sides.forward) + local iter = inventory.getAllStacks(sides.forward) + local slot = 1 local empty_slot = -1 - for slot = 1, size do - local stack = inventory.getStackInSlot(sides.forward, slot) - if stack then + local stack = iter() + while stack do + if stack.name then if stack.name == item.name then inventory.dropIntoSlot(sides.forward, slot) -- check if all items have been stored @@ -124,6 +129,8 @@ local function store_item() empty_slot = slot end end + stack = iter() + slot = slot + 1 end -- item not present in inventory @@ -157,20 +164,23 @@ local function fetch_item(item, output_slot, count) local name, damage = parse_item(item, ";") robot.select(output_slot) - local size = inventory.getInventorySize(sides.forward) - if not size then + local iter = inventory.getAllStacks(sides.forward) + if not iter then print('Not facing a chest') return false end - for slot = 1, size do - local stack = inventory.getStackInSlot(sides.forward, slot) - if stack then + local stack = iter() + local slot = 1 + while stack do + if stack.name then if stack.name == name and stack.damage == damage then inventory.suckFromSlot(sides.forward, slot, count) return true end end + stack = iter() + slot = slot + 1 end print('Missing ' .. item)