This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Zintoras's profile picture

turtle.getItemCount and turtle.select loop

Started by Zintoras, 02 December 2013 - 01:16 AM
Zintoras #1
Posted 02 December 2013 - 02:16 AM
Im new to the forum and programming so i need help pls
I need a loop that detects if there is an item in slot 1-16 if not go to the next slot and i dont know how to do that.
the program i made creates a part for a mobspawner








for trap=1,4 do

for ry=1,3 do

for w=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnRight()
turtle.forward()
turtle.turnRight()

for yc=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()

end

for qs=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnRight()
turtle.forward()
turtle.turnRight()

for ts=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()

for tz=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnRight()
turtle.forward()
turtle.down()
turtle.turnRight()

for ty=1,9 do
turtle.placeDown()
turtle.forward()
end

turtle.back()
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()

for qy=1,9 do
turtle.Down()
turtle.forward()
end

turtle.back()
turtle.turnRight()
turtle.up()
turtle.forward()

end
Buho #2
Posted 02 December 2013 - 11:48 AM
What you ask for is a common design problem I run into a lot. Try this:


function selectItem()
    for s = 1, 16 do
        if turtle.getItemCount(s) > 1 then
            turtle.select(s)
            return true
        end
    end
    return false
end

This is a little, self-contained function that will simply select a slot with inventory. I put > 1 to preserve the catalog in the inventory (useful if you have more than one kind of item in the inventory). If your inventory is all the same, change that to > 0.

To use:


selectItem()
turtle.placeDown()

You could wrap the two lines into another function to make it easier to maintain and self-document:


function placeItem()
    if selectItem() then
        turtle.placeDown()
    else
        error("Ran out of inventory!")
    end
end

And to use:


placeItem()

Hope that helps.
Edited on 02 December 2013 - 10:54 AM
Zintoras #3
Posted 02 December 2013 - 12:32 PM
Thank you very much works perfect now i didtn thought of a function i tried it with while loops i note this for the next time ill need