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

[LUA] [Question] Shorten this code?

Started by campop1, 22 December 2012 - 11:14 AM
campop1 #1
Posted 22 December 2012 - 12:14 PM
Hey guys I'm pretty new to this community and I only recently started trying to make ComputerCraft programs. I have a program that I wrote to automatically chop down trees and and deposit the logs into a chest. Currently the method I'm using to deposit the logs is really long and I'm sure there is some kind of loop I can use to shorten it. But being the beginner I am I don't know how exactly. The current code goes like this:


turtle.getItemCount(16)
if turtle.getItemCount(16) >= 64 then
  turtle.turnRight()
  turtle.turnRight()
  turtle.select(5)
  turtle.drop()
  turtle.select(6)
  turtle.drop()
  turtle.select(7)
  turtle.drop()
  turtle.select(8)
  turtle.drop()
  turtle.select(9)
  turtle.drop()
  turtle.select(10)
  turtle.drop()
  turtle.select(11)
  turtle.drop()
  turtle.select(12)
  turtle.drop()
  turtle.select(13)
  turtle.drop()
  turtle.select(14)
  turtle.drop()
  turtle.select(15)
  turtle.drop()
  turtle.select(16)
  turtle.drop()
  turtle.turnLeft()
  turtle.turnLeft()
end

Any help as to how I could make a loop to cycle through inventory slots and drop items into a chest would be appreciated.
Fizzgig #2
Posted 22 December 2012 - 12:27 PM
here ya go you want to use a for loop

turtle.getItemCount(16)
if turtle.getItemCount(16) >= 64 then
turtle.turnRight()
turtle.turnRight()

for i=5,16 do
  turtle.select(i)
  turtle.drop()
end

turtle.turnLeft()
turtle.turnLeft()
end

i is a variable name (can be anything) and it is set to i=5 this is the start of the loop, counts to 16

for i=5,16 do
–stuff to do
end
ChunLing #3
Posted 22 December 2012 - 12:31 PM
See the Tutorials section for many more fine coding tips.
campop1 #4
Posted 22 December 2012 - 12:40 PM
Thanks so much buddy. I thought it would be a for loop but I didn't know how to set it out, but now I understand, you sir have been a great help.
Sammich Lord #5
Posted 22 December 2012 - 12:42 PM
Thanks so much buddy. I thought it would be a for loop but I didn't know how to set it out, but now I understand, you sir have been a great help.
If you need to find the usage for any thing in Lua, just google "Lua functionNameGoesHere usage".