trainworld_computercraft/computer/13/inventory.lua
2025-05-23 15:45:14 +02:00

119 lines
2.4 KiB
Lua

pp = require("cc.pretty")
function pFront(fn, ...)
return peripheral.call("front", fn, unpack(arg))
end
function pBottom(fn, ...)
return peripheral.call("bottom", fn, unpack(arg))
end
function pTop(fn, ...)
return peripheral.call("top", fn, unpack(arg))
end
function findItems(item_list, target)
for i, v in pairs(item_list) do
if stripModname(v.name) == target then
return i
end
end
return nil
end
function takeItems(type, count)
local item_list = pFront("list")
local slot = findItems(item_list, type)
if slot == nil then
printError("could not find item " .. type .. " in chest")
return false
end
if slot ~= 1 then
local size = pFront("size")
local empty_slot = nil
for i = 1, size do
if pFront("getItemDetail", i) == nil then
empty_slot = i
break
end
end
if empty_slot == nil then
printError("no empty slot in chest, pls fix")
exit()
end
if empty_slot ~= 1 then
pFront("pullItems", "front", 1, 64, empty_slot) -- empty first slot
end
pFront("pullItems", "front", slot, 64, 1) -- get target item to first slot
end
return turtle.suck(count)
end
function selectItem(name, has_nbt)
has_nbt = has_nbt or false
if name == nil or name == "nil" then
for i = 1, 16 do
if turtle.getItemCount(i) == 0 then
turtle.select(i)
return
end
end
printError("no empty slot found")
return
end
for i = 1, 16 do
detail = turtle.getItemDetail(i, true);
if detail and stripModname(detail.name) == name then
if has_nbt == (detail.nbt ~= nil) then
turtle.select(i)
return
end
end
end
printError("missing item", name, "nbt=", has_nbt)
end
function getMissing(needed_items)
missing = {}
for name, count in pairs(needed_items) do
missing[name] = count
end
target_contents = pFront("list")
for _, target_item in pairs(target_contents) do
for name, missing_count in pairs(missing) do
if stripModname(target_item.name) == name then
missing[name] = missing_count - target_item.count
if missing[name] < 1 then
missing[name] = nil
end
break
end
end
end
pp.pretty_print(missing)
return missing
end
function insertForward(slot, count)
turtle.dropDown(count)
pFront("pullItems", "bottom", 1, 64, slot)
end
function takeForward(slot)
pBottom("pullItems", "front", slot or 1)
turtle.suckDown()
end
function insertDepot(count)
turtle.dropDown(count)
pFront("pullItem", "bottom")
end
function takeDepot()
pFront("pushItem", "bottom")
turtle.suckDown()
end