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

Mining turtle program

Started by saikit555, 30 May 2013 - 12:02 PM
saikit555 #1
Posted 30 May 2013 - 02:02 PM
I worte a program to strip mine..but the turtle ends up at a different spot every time i run the program. :(/>
Still new to programming and i appreciate if someone could tell me what's wrong with my code.

Spoiler
 --Variables!

local miningLength = 50
local movingLength = 4

--Functions!

function dig()
while turtle.detect()do
      turtle.dig()
      sleep(1)
end
  end      

function digUp()
while turtle.detectUp()do
      turtle.digUp()
      sleep(1)
end      
  end

function turnRight2()
turtle.turnRight()
turtle.turnRight()
end

function turnLeft2()
turtle.turnLeft()
turtle.turnLeft()
end

function path()
if not turtle.detectDown() then
       turtle.select(2)
       turtle.placeDown()
end
  end    


--Program!  

for i= 1,miningLength, 1 do

if turtle.getFuelLevel() <100 then
   turtle.refuel(1)
   print("Refuel!")
end

print("mining...")

dig()

turtle.forward()
turtle.turnLeft()

dig()

turnRight2()

dig()

digUp()

turtle.up()

dig()

turnLeft2()

dig()

digUp()

turtle.up()

dig()

turnRight2()

dig()

turtle.turnLeft()
turtle.down()
turtle.down()

path()

end

miningLength = 50
for i = 1,miningLength,1 do
    turtle.back()
end

turtle.select(16)
turtle.placeUp()
sleep(1)

turtle.select(2)
turtle.dropUp()
turtle.select(3)
turtle.dropUp()
turtle.select(4)
turtle.dropUp()
turtle.select(5)
turtle.dropUp()
turtle.select(6)
turtle.dropUp()
turtle.select(7)
turtle.dropUp()
turtle.select(8)
turtle.dropUp()
turtle.select(9)
turtle.dropUp()
turtle.select(10)
turtle.dropUp()
turtle.select(11)
turtle.dropUp()
turtle.select(12)
turtle.dropUp()
turtle.select(13)
turtle.dropUp()
turtle.select(14)
turtle.dropUp()
turtle.select(15)
turtle.dropUp()
sleep(1)

turtle.select(16)
turtle.digUp()
print("Done")
sleep(1)

turtle.turnRight()
turtle.forward()

movingLength = 5 

for i = 1,movingLength,1 do

dig()

turtle.turnLeft()

dig()

turnRight2()

dig()

digUp()

turtle.up()

dig()

turnLeft2()

dig()     

digUp()

turtle.up()

dig()

turnRight2()

dig()

turtle.turnLeft()
turtle.down()
turtle.down()

path()
turtle.forward()                          
end

turtle.back()
turtle.turnLeft()
print("Ready to mine again.") 
Edited by
Lyqyd #2
Posted 30 May 2013 - 02:32 PM
Split into new topic.
angellus #3
Posted 30 May 2013 - 03:03 PM
If you are new to programming, great job so far! The code looks like it should work fine without any complications. I went through and added some comments to your code. There is one really important one for why your turtle might not always be ending up in the correct place. "turtle.forward()" does NOT move the turtle forward. It TRIES to move the turtle forward and returns a boolean (true/false) if it is successful. This is where the complications can come in. I added a while loop in a comment to illustrate how to check if it moved forward. Mobs, players and blocks can prevent a turtle from moving forward. So you want dig and attack there. Be careful though, the turtle can kill you too ;)/>

Spoiler

--Variables!
local miningLength = 50
local movingLength = 4
--Functions!
function dig()
	while turtle.detect()do
		turtle.dig()
		sleep(1)
	end
end	
function digUp()
	while turtle.detectUp()do
		turtle.digUp()
		sleep(1)
	end	
end
function turnRight2() -- you do not need both turnRight2 and turnLeft2. They do the same thing really (turn the turtle 180 degrees)
	turtle.turnRight()
	turtle.turnRight()
end
function turnLeft2()
	turtle.turnLeft()
	turtle.turnLeft()
end
function path()
	if not turtle.detectDown() then
		turtle.select(2)
		turtle.placeDown()
	end
end  

--Program!
function main() -- Always encase your main program into a function, good practice and saves you the headache sometimes
	for i= 1,miningLength do -- for i= 1,miningLength, 1 do <- do not need the third var, 1 is what it is by default
		if turtle.getFuelLevel() <100 then -- this 100 hunderd might be a good number to put in a varible at the top, so you can change it later (if you change mininglength/movinglength
		   turtle.refuel(1) -- Same with the slot num here
		   print("Refuel!")
		end
		print("mining...")
		dig()
		turtle.forward() -- did the turtle actually move forward?
		-- while not turtle.forward() do
		--   turtle.attack()
		--   turtle.dig()
		--   sleep(1)
		-- end
		turtle.turnLeft()
		dig()
		turnRight2()
		dig()
		digUp()
		turtle.up()
		dig()
		turnLeft2()
		dig()
		digUp()
		turtle.up()
		dig()
		turnRight2()
		dig()
		turtle.turnLeft()
		turtle.down()
		turtle.down()
		path()
	end
  
	--miningLength = 50 -- Do not need to reset miningLength, for loop does not affect the var
	for i = 1,miningLength,1 do -- again, do not need the last 1 really
		turtle.back()
	end
  
	turtle.select(16) -- what are you using for storage that you just place it and then pick it back up?
	turtle.placeUp()
	sleep(1)
  
	turtle.select(2) -- Loop!
	turtle.dropUp()  -- for x=2, 15 do
	turtle.select(3) --  turtle.select(x)
	turtle.dropUp()  --  turtle.dropUp()
	turtle.select(4) -- end
	turtle.dropUp()
	turtle.select(5)
	turtle.dropUp()
	turtle.select(6)
	turtle.dropUp()
	turtle.select(7)
	turtle.dropUp()
	turtle.select(8)
	turtle.dropUp()
	turtle.select(9)
	turtle.dropUp()
	turtle.select(10)
	turtle.dropUp()
	turtle.select(11)
	turtle.dropUp()
	turtle.select(12)
	turtle.dropUp()
	turtle.select(13)
	turtle.dropUp()
	turtle.select(14)
	turtle.dropUp()
	turtle.select(15)
	turtle.dropUp() -- Loop end
	sleep(1)
  
	turtle.select(16)
	turtle.digUp()
	print("Done")
	sleep(1)
  
	turtle.turnRight()
	turtle.forward()
  
	movingLength = 5 -- again, do not really need to reset this, HOWEVER, this one is different then the one at the top
  
	for i = 1,movingLength,1 do -- again, do not need the last 1 really
		dig()
		turtle.turnLeft()
		dig()
		turnRight2()
		dig()
		digUp()
		turtle.up()
		dig()
		turnLeft2()
		dig()	
		digUp()
		turtle.up()
		dig()
		turnRight2()
		dig()
		turtle.turnLeft()
		turtle.down()
		turtle.down()
		path()
		turtle.forward()						
	end
  
	turtle.back()
	turtle.turnLeft()
	print("Ready to mine again.")
end
main()
saikit555 #4
Posted 31 May 2013 - 11:20 AM
Thanks! :)/> You really helped alot. The only thing i could get was to add refuel as a variable.
BTW i would like to be able to be able to tell the turtle the mining length and how many times it runs the program without going in to the program to change it(E.g. mine <tunnel length> <no. of times>) . If anyone could help with that it would be nice. :)/>

Spoiler
--Variables!

local miningLength = 2
local movingLength = 4
local minFuelLevel = 100
local refuel = 1
local chestSlot = 16
local minChest = 1

--Functions!

function refuel()
if turtle.getFuelLevel() <minFuelLevel then
   turtle.refuel(1)
end
print("Refuel!")
sleep(1)
end

function dig()
while turtle.detect()do
      turtle.dig()
      sleep(1)
end
  end      

function digUp()
while turtle.detectUp()do
      turtle.digUp()
      sleep(1)
end      
  end

function rotate()
turtle.turnRight()
turtle.turnRight()
end

function forward()
while not turtle.forward() do
          turtle.attack()
          turtle.dig()
          sleep(1)
end
  end

function path()
while not turtle.detectDown()do
          turtle.select(2)
          turtle.placeDown()
end
  end    

function placeChest()
while turtle.getItemCount(16) ~= minChest do
      print("No chest!")
      sleep(10)
end      
turtle.select(chestSlot)
turtle.placeUp()
sleep(1)
end

function emptyInv()
for x = 2, 15 do
turtle.select(x)
turtle.dropUp()
end
  end

--EnderChest
function takeChest()
turtle.select(16)
turtle.digUp()
print("Got EnderChest!")
sleep(1)
end  

--Program!  

function main()

for i= 1,miningLength do

refuel()
print("mining...")

dig()

forward()
turtle.turnLeft()

dig()

rotate()

dig()

digUp()

turtle.up()

dig()

rotate()

dig()

digUp()

turtle.up()

dig()

rotate()

dig()

turtle.turnLeft()
turtle.down()
turtle.down()

path()

end

rotate()

for i = 1,miningLength do
    forward()
end

--Put Chest or EnderChest in slot 16

placeChest()
emptyInv()

--For EnderChest(delete if not using EnderChest)
takeChest()

turtle.turnLeft()
forward()

for i = 1,movingLength do

dig()

forward()
turtle.turnLeft()

dig()

rotate()

dig()

digUp()

turtle.up()

dig()

rotate()

dig()     

digUp()

turtle.up()

dig()

rotate()

dig()

turtle.turnLeft()
turtle.down()
turtle.down()

path()                          
end

turtle.back()
turtle.turnLeft()
print("Ready to mine again.")
end
main()
W00dyR #5
Posted 31 May 2013 - 11:31 AM

local args = {...} -- This reads the arguments, and puts them into a table

if #args ~= 2 then -- This if loop checks the arguments, and if there arent 2 arguments, it will print how to use it / quit the program
  print("Syntax: mine <tunnel length> <no. of times>")
  return
end

local length = tonumber(args[1]) -- These 2 variables read the table and sets them from string to number, these will be your variables for length and # of times
local noOfTimes= tonumber(args[2])

I made a simple code for you as you see, if you enter arguments that cannot be converted to a number, it will error. A simple fix for this is something like:


if not length or noOfTimes then
  print("Syntax: mine <tunnel length> <no. of times>")
  return
end

This check works because "tonumber(args[1])" returns a boolean value, so you check the boolean value pretty much. Good luck :)/>
saikit555 #6
Posted 31 May 2013 - 11:45 AM
 local args = {...} -- This reads the arguments, and puts them into a table if #args ~= 2 then -- This if loop checks the arguments, and if there arent 2 arguments, it will print how to use it / quit the program print("Syntax: mine  ") return end local length = tonumber(args[1]) -- These 2 variables read the table and sets them from string to number, these will be your variables for length and # of times local noOfTimes= tonumber(args[2]) 
I made a simple code for you as you see, if you enter arguments that cannot be converted to a number, it will error. A simple fix for this is something like:
 if not length or noOfTimes then print("Syntax: mine  ") return end 
This check works because "tonumber(args[1])" returns a boolean value, so you check the boolean value pretty much. Good luck :)/>/&amp;gt;/&amp;gt;
Where in the code should these be placed?
Edited on 31 May 2013 - 09:45 AM
W00dyR #7
Posted 31 May 2013 - 11:52 AM
Where in the code should these be placed?

On the first lines, because all the code does is read input, declare variables, and a way of stopping the program if the input is invalid. So instead of the variables you posted in your original code, use the part I posted. You can ofcourse rename the "local length" and "local noOfTimes" to the way you had it before (miningLength and movingLength)
saikit555 #8
Posted 31 May 2013 - 12:07 PM
Where in the code should these be placed?
On the first lines, because all the code does is read input, declare variables, and a way of stopping the program if the input is invalid. So instead of the variables you posted in your original code, use the part I posted. You can ofcourse rename the "local length" and "local noOfTimes" to the way you had it before (miningLength and movingLength)
Thanks. :)/> I made the mistake of placing local mining length before the local args but the second argument i would like to make is not the moving length but how many times it runs the whole program. Is that possible?
W00dyR #9
Posted 31 May 2013 - 12:17 PM
Thanks. :)/> I made the mistake of placing local mining length before the local args but the second argument i would like to make is not the moving length but how many times it runs the whole program. Is that possible?

Of course, you can rename the variable into anything you want, and use that variable throughout your code, or are you requesting the method of making your code run x amount of times? Because that is simply done using a for loop, which you used before in your original code so I assume you know how that works.

The way it works is just like this:


local args = {...}
local variableOne = tonumber(args[1])
local variableTwo = tonumber(args[2])

If the syntax for the code to work would be "dig <length> <depth>", then if I type "dig 10 5", in the code above the variableOne = 10, and variableTwo = 5. So the way it works is that it its just like typing variableOne = 10, but instead of that the code reads the users input and sets that to be the variable.

(Typing this in a hurry, dinner's ready, if you don't understand, please reply, I'll try explain after dinner :P/>)
saikit555 #10
Posted 31 May 2013 - 01:02 PM
Thanks. :)/>/> I made the mistake of placing local mining length before the local args but the second argument i would like to make is not the moving length but how many times it runs the whole program. Is that possible?
Of course, you can rename the variable into anything you want, and use that variable throughout your code, or are you requesting the method of making your code run x amount of times? Because that is simply done using a for loop, which you used before in your original code so I assume you know how that works. The way it works is just like this:
 local args = {...} local variableOne = tonumber(args[1]) local variableTwo = tonumber(args[2]) 
If the syntax for the code to work would be "dig ", then if I type "dig 10 5", in the code above the variableOne = 10, and variableTwo = 5. So the way it works is that it its just like typing variableOne = 10, but instead of that the code reads the users input and sets that to be the variable. (Typing this in a hurry, dinner's ready, if you don't understand, please reply, I'll try explain after dinner :P/>/>)
oh.thanks again. I didn't think of using the for loop together with the variable with the argument. :)/> Would you happen to know how to add a line that if inventory full it would empty into a chest?
W00dyR #11
Posted 31 May 2013 - 01:13 PM
Would you happen to know how to add a line that if inventory full it would empty into a chest?

Yes you can make easy use of the turtle.getItemCount() function. If you want it to be checked with every block that has been dug, my advice is to make a simple function that counts the items, if its full inventory it will place a chest and drop its items in there. You can also have it map out where it went, and return to the start but that would make things much more complicated.

For example, I wrote you this quick function (this will need you to put a chest in its 16th slot)


local function inventoryCheck()
  if turtle.getItemCount(15) ~= 0 then -- Checks the 15th inventory slot
	turtle.select(16) -- Selects the 16th slot (which contains a chest)
	turtle.turnRight() -- Turns around
	turtle.turnRight()
	if turtle.detect() then -- Checks if there is a block, if yes, it digs it out
	  turtle.dig()
	end
	turtle.place() -- Places the chest
	for i = 1, 15 do -- For slot 1 till 15, it selects the slot and drops its contents in the chest
	  turtle.select(i)
	  turtle.drop()
	end
	turtle.turnRight() -- Turns back so it faces front
	turtle.turnRight()
	turtle.select(1)
  end
end

Of course this has a few flaws, it will not know what direction it faces, it just turns around to where it came from (I assume) and places a chest, then empties the inventory, and moves on.
saikit555 #12
Posted 31 May 2013 - 01:24 PM
Would you happen to know how to add a line that if inventory full it would empty into a chest?
Yes you can make easy use of the turtle.getItemCount() function. If you want it to be checked with every block that has been dug, my advice is to make a simple function that counts the items, if its full inventory it will place a chest and drop its items in there. You can also have it map out where it went, and return to the start but that would make things much more complicated. For example, I wrote you this quick function (this will need you to put a chest in its 16th slot)
 local function inventoryCheck() if turtle.getItemCount(15) ~= 0 then -- Checks the 15th inventory slot turtle.select(16) -- Selects the 16th slot (which contains a chest) turtle.turnRight() -- Turns around turtle.turnRight() if turtle.detect() then -- Checks if there is a block, if yes, it digs it out turtle.dig() end turtle.place() -- Places the chest for i = 1, 15 do -- For slot 1 till 15, it selects the slot and drops its contents in the chest turtle.select(i) turtle.drop() end turtle.turnRight() -- Turns back so it faces front turtle.turnRight() turtle.select(1) end end 
Of course this has a few flaws, it will not know what direction it faces, it just turns around to where it came from (I assume) and places a chest, then empties the inventory, and moves on.
Can i use functions within a function?
W00dyR #13
Posted 31 May 2013 - 01:33 PM
Can i use functions within a function?

Yes you can call functions within functions, as long as they have been declared. Functions can call themselves to, up to a limit of 256 I think (correct me if I'm wrong) but for a dig function that also checks the mined blocks you could have the inventoryCheck() as one of the first few functions that is declared. Then dig() would be something like:


local function dig()
  inventoryCheck()
  while turtle.detect() do
    turtle.dig()
    sleep(1)
  end
end
saikit555 #14
Posted 31 May 2013 - 01:55 PM
Can i use functions within a function?
Yes you can call functions within functions, as long as they have been declared. Functions can call themselves to, up to a limit of 256 I think (correct me if I'm wrong) but for a dig function that also checks the mined blocks you could have the inventoryCheck() as one of the first few functions that is declared. Then dig() would be something like:
 local function dig() inventoryCheck() while turtle.detect() do turtle.dig() sleep(1) end end 
Thanks. May i ask why do type local function instead of just function and return end instead of just end?
W00dyR #15
Posted 31 May 2013 - 02:17 PM
May i ask why do type local function instead of just function and return end instead of just end?

Its not something like a requirement, I just like using "local function" so that, just incase, it interferes with any other API or anything, it stays local.

Using "return" stops the program and returns to its shell. I use that to abort a program if the input isn't right. For example, in the checks that check if you have the correct set of arguments, if you don't add the "return" it will simply print the syntax, and then continue executing the program. So it will also print the errors that follow due to incorrect input.
angellus #16
Posted 31 May 2013 - 03:37 PM
May i ask why do type local function instead of just function and return end instead of just end?

Its not something like a requirement, I just like using "local function" so that, just incase, it interferes with any other API or anything, it stays local.

Using "return" stops the program and returns to its shell. I use that to abort a program if the input isn't right. For example, in the checks that check if you have the correct set of arguments, if you don't add the "return" it will simply print the syntax, and then continue executing the program. So it will also print the errors that follow due to incorrect input.

It is also good programming practice. If you get into programming more you will get to scoping. Scoping is basically how high up a variable (or function) can be accessed. In Lua, if you add "local" in front of a variable or function it means it canonly be in that block of code or scope. There are different levels of scoping and you can go in as far as you want (nesting). If you do not put local, it makes it global so any thing can access it. Here is an example (sorry if it confuses you, scoping is a late-beginner/intermediate topic, plus I suck at teaching):

SpoilerHere is how shell is scoped at different places:

On the global level (Lua Interruper):
shell is a table that points to the shell object

In a file:

print(tostring(shell)) -- still the table that points to the shell object
local shell = 3 -- shell is now 3, but ONLY in this file
local function someFunc()
	print(tostring(shell)) -- still 3, inherts scope from the file
	local shell = 2
	print(tostring(shell))-- now it is 2
   for x=1,10 do
	   print(tostring(shell)) -- still 2
   end
   for x=1,10 do
	   local shell = 1
	   print(tostring(shell)) -- now it is 1
   end
   print(tostring(shell)) -- 2 here. The loop is now out of scope
end
print(tostring(shell)) -- 3 here. SomeFunc is now out of scope
Back outside of the file, scope is still that table. You never touched it. However, if you do not use that local when you first change the variable, you will change this global one for shell.

Of course the obvious solution is do not use a variable called shell, but it might not be that easy. What if it was a more generic variable, like "x" for a counter? Or "x" for a coordinate?

EDIT: Linky: http://lua-users.org/wiki/ScopeTutorial

Also, using return is good practice too. This way you know you are returning exactly what you mean to: nothing. Sometimes you might want to return a variable back, like


function add(one, two)
	 return one+two
end

is a simple function to add two numbers.
Bomb Bloke #17
Posted 31 May 2013 - 06:50 PM
Note that any local functions must be declared above any functions that call them.
saikit555 #18
Posted 01 June 2013 - 12:42 PM
Thanks for all your inputs. It really taught me a lot about basic programming.
saikit555 #19
Posted 01 June 2013 - 12:49 PM
Found something wrong with my program.


function path()
while not turtle.dectectDown() do
               turtle.select(2)
               turtle.placeDown()
end
   end

If it mines something else and place it in slot 2 like(e.g. coal, diamonds,redstone,etc.) it will just stop. How do i make it try slot 2 and if it fails try slot 3 etc. until it succeeds.(or should i just make it keep a slot with blocks just to path?)

Edit: oh and i try to do

local refuel = 1

turtle.refuel(refuel)
--and
turtle.refuel() = refuel

both doesn't work. How do you do this properly?
angellus #20
Posted 01 June 2013 - 02:29 PM
here you go:

function path()
    while not turtle.detectDown() do
	    local slot = 2 -- starting slot
	    turtle.select(slot)
	    while not turtle.placeDown() do -- loop through until success
		    slot = slot + 1
		    if slot &amp;gt; 16 then
			    term.write("Enter more materials. and press ENTER") -- out of stuff D:
			    read()
			    slot = 2
		    end
		    turtle.select(slot)
	    end
    end
end



local refuelSlot = 1
turtle.select(refuelSlot)
turtle.refuel()
saikit555 #21
Posted 02 June 2013 - 12:19 PM
here you go:
 function path() while not turtle.detectDown() do local slot = 2 -- starting slot turtle.select(slot) while not turtle.placeDown() do -- loop through until success slot = slot + 1 if slot &amp;amp;amp;gt; 16 then term.write("Enter more materials. and press ENTER") -- out of stuff D: read() slot = 2 end turtle.select(slot) end end end local refuelSlot = 1 turtle.select(refuelSlot) turtle.refuel() 
What's the differents between term.write and print? They seem to do the same thing..but there's a differents right?
Edit: and the refuel i was wondering how to set a variable for how many coal it consumes each time not which slot it uses.
Edit:
Spoiler

local function path()
               while not turtle.detectDown()do
                         local slot = 2
                         turtle.select(slot)
                         while not turtle.placeDown() do 
                                   slot = slot + 1
                                   if slot &amp;gt; 16 then
                                           term.write(Enter more materials. and press ENTER")
                                           read()

                                           slot = 2
                                   end 
                                   turtle.select(slot)
                         end
               end
end               

using a lua editor to edit this in. when debug gets Syntax: then expected near '&amp;'.why?
GopherAtl #22
Posted 02 June 2013 - 12:21 PM
the write functions do not add a newline at the end, so you use write for prompts where you want the user to type into the same line, or when writing text to the bottom of the screen without making it scroll up.

There's term.write() and write(), which have a difference. term.write doesn't understand escape characters like \n, which can be used to manually insert newlines in output. write() does understand these. write() also does word-based line wrapping when it goes past the edge of the screen, while term.write() does not.
saikit555 #23
Posted 02 June 2013 - 03:27 PM
hmm…what happens if i use a for loop for torch placing but my mining length is not a multiple of it.
for example could i do:

local length = 50
local torchInterval = 8

for i = 1,length/torchInterval do
           main() --e.g. main is a code that mines 8 rows at a time
end

what would happen?
Bomb Bloke #24
Posted 02 June 2013 - 07:06 PM
The loop will round your division results down. 50/8 = 6.25, so main() will be called six times, and at eight rows/per that means 48 rows will be dug.
GopherAtl #25
Posted 02 June 2013 - 11:31 PM
it would be more conventioanl to loop over the total distance, and use % (modulo, or remainder of integer division) to space torches, example:


local spacing=8

for i=1,length do
  turtle.dig()
  turtle.forward()
  turtle.digUp()
  --this will be true every "spacing" blocks
  if i%spacing==0 then
    turtle.place() --assumes torches selected
  end
end

This is obviously just an example, not a very smart shaft program in general but it demonstrates using % to do something only at intervals in a loop.
saikit555 #26
Posted 03 June 2013 - 05:21 AM
it would be more conventioanl to loop over the total distance, and use % (modulo, or remainder of integer division) to space torches, example:
 local spacing=8 for i=1,length do turtle.dig() turtle.forward() turtle.digUp() --this will be true every "spacing" blocks if i%spacing==0 then turtle.place() --assumes torches selected end end 
This is obviously just an example, not a very smart shaft program in general but it demonstrates using % to do something only at intervals in a loop.
could you explain more? when would i%spacing == 0?
theoriginalbit #27
Posted 03 June 2013 - 05:33 AM
could you explain more? when would i%spacing == 0?
modulo/modulus (%) divides number 1 (left) by number 2 (right) until it can no longer be divided and returns the remainder after so. For example:

9 % 3 = 0 as 3 goes into 9 3 times with a remainder of 0
10 % 3 = 1 as 3 goes into 10 3 times with a remainder of 1
11 % 3 = 2 as 3 goes into 11 3 times with a remainder of 2
12 % 3 = 0 as 3 goes into 12 4 times with a remainder of 0

example with another number
20 % 5 = 0
21 % 5 = 1
22 % 5 = 2
23 % 5 = 3
24 % 5 = 4
25 % 5 = 0
26 % 5 = 1
etc……

does that make sense?
saikit555 #28
Posted 03 June 2013 - 06:11 AM
could you explain more? when would i%spacing == 0?
modulo/modulus (%) divides number 1 (left) by number 2 (right) until it can no longer be divided and returns the remainder after so. For example: 9 % 3 = 0 as 3 goes into 9 3 times with a remainder of 0 10 % 3 = 1 as 3 goes into 10 3 times with a remainder of 1 11 % 3 = 2 as 3 goes into 11 3 times with a remainder of 2 12 % 3 = 0 as 3 goes into 12 4 times with a remainder of 0 example with another number 20 % 5 = 0 21 % 5 = 1 22 % 5 = 2 23 % 5 = 3 24 % 5 = 4 25 % 5 = 0 26 % 5 = 1 etc…… does that make sense?
yes. thanks.
saikit555 #29
Posted 03 June 2013 - 06:23 AM
Does a program remember an argument variable until the program ends?

example:

local x = tonumber (args [1]) --i entered 1
local y = tonumber (args [2]) -- i entered 2

if #args ~= 2 then
   print("Syntax: <x> <y>")
  return
end

print(x) --these would still be 1 and 2?
print(y)

theoriginalbit #30
Posted 03 June 2013 - 06:35 AM
all localised variables and functions are stored in memory until they are no longer referenced, which most of the time is when the program has finished running. They can last longer than the program runtime, very rarely do the last less than the program runtime.
saikit555 #31
Posted 03 June 2013 - 06:59 AM
Spoiler

local function path()
               while not turtle.detectDown()do
                         local slot = 2
                         turtle.select(slot)
                         while not turtle.placeDown() do 
                                   slot = slot + 1
                                   if slot &amp;amp;gt; 16 then
                                           term.write(Enter more materials. and press ENTER")
                                           read()

                                           slot = 2
                                   end 
                                   turtle.select(slot)
                         end
               end
end               

using a lua editor to edit this in. when debug gets Syntax: then expected near '&amp;amp;'.why?
theoriginalbit #32
Posted 03 June 2013 - 07:09 AM
because this
if slot &amp;amp;gt; 16 then
is not valid at all in lua. &amp;amp;gt; is not lua
it should read something like this (i assume)
if slot > 16 then
not too sure what you intend to actually do with this. also your term.write string is missing an opening "
lastly if you use term.write you will not have any line wrapping and such, you're better to use write or print.
saikit555 #33
Posted 03 June 2013 - 09:29 AM
Found something wrong with my program.
 function path() while not turtle.dectectDown() do turtle.select(2) turtle.placeDown() end end 
If it mines something else and place it in slot 2 like(e.g. coal, diamonds,redstone,etc.) it will just stop. How do i make it try slot 2 and if it fails try slot 3 etc. until it succeeds.(or should i just make it keep a slot with blocks just to path?) Edit: oh and i try to do
 local refuel = 1 turtle.refuel(refuel) --and turtle.refuel() = refuel 
both doesn't work. How do you do this properly?

here you go:
 
function path() 
while not turtle.detectDown() do 
          local slot = 2 -- starting slot 
          turtle.select(slot) 
          while not turtle.placeDown() do -- loop through until success 
                    slot = slot + 1 
                     if slot &amp;amp;amp;gt; 16 then 
                        term.write("Enter more materials. and press ENTER") -- out of stuff D: 
                        read() 
                        slot = 2 
                     end 
                     turtle.select(slot) 
         end 
end 
 end 
because this
if slot &amp;amp;amp;amp;gt; 16 then
is not valid at all in lua. &amp;amp;amp;amp;gt; is not lua it should read something like this (i assume)
if slot &amp;amp;gt; 16 then
not too sure what you intend to actually do with this. also your term.write string is missing an opening " lastly if you use term.write you will not have any line wrapping and such, you're better to use write or print.
So how would i do it?
theoriginalbit #34
Posted 03 June 2013 - 09:44 AM
So how would i do it?
Do what?
saikit555 #35
Posted 03 June 2013 - 09:49 AM
So how would i do it?
Do what?
A path function.

function path()
         while not turtle.dectectDown() do 
                   turtle.select(2) 
                   turtle.placeDown()
         end 
end 
it trys slot 2 first if it not place-able(example:redstone) i moves on to slot 3, 4 etc. until it places it.
Bomb Bloke #36
Posted 03 June 2013 - 10:16 AM
if slot &amp;amp;amp;amp;gt; 16 then

:D/>

function path()
         local pathcounter = 2
         while not turtle.dectectDown() do 
                   turtle.select(pathcounter)
                   turtle.placeDown()
                   pathcounter = pathcounter + 1
         end 
end
theoriginalbit #37
Posted 03 June 2013 - 10:29 AM
:D/>

function path()
		 local pathcounter = 2
		 while not turtle.dectectDown() do
				   turtle.select(pathcounter)
				   turtle.placeDown()
				   pathcounter = pathcounter + 1
		 end
end
The turtle.select statement would error the program when pathcounter is above 16, hence the if statement, which saikit555 can't seem to put into the program because > keeps turning into &amp;gt;

EDIT: So that being said, here is the solution that html won't mess up on you…
Spoiler

function path()
  local slot = 2
  turtle.select(slot) --# initial select
  while not turtle.dectectDown() do
	turtle.select(slot)
	turtle.placeDown()
	slot = slot + 1
	if slot == 17 then --# we have gone beyond the inventory
	  print('Nothing could be placed, please supply more materials and press enter')
	  while true do
		local e, k = os.pullEvent('key')
		if k == keys.enter then break end
	  end
	  slot = 2 --# get ready to start checking again
	end
  end
end
Edited on 03 June 2013 - 08:46 AM
saikit555 #38
Posted 03 June 2013 - 03:01 PM
Thanks for all your help. :)/>/&amp;gt;/&amp;amp;gt;

Here is the edited code after all the help with it. Still not done with it though.
Spoiler


local args = {...}
local noOfTunnel = tonumber(args[1]) 	-- number of tunnels to be mined
local miningLength = tonumber(args[2])  --length of each tunnel
local movingLength = 4 					--reposition length to next tunnel 
local minFuelLevel = 100                -- minimum fuel level before starting
local refuel = 1                        --fuel slot
local minChest = 1                      --minimum number of chest 
local chestSlot = 2                     --chest slot
local torchSlot = 3                     -- torch slot
local inventory = 4                     --where inventory begins
local torchInterval = 8                 --how many block between torch placement 

--Arguments!
if #args ~= 2 then
   print("Syntax: mine <no. of tunnels> <length of tunnels>")
  return
end

--Functions!

local function refuel() --Checks fuel level and refuels turtle
         	   if turtle.getFuelLevel() <minFuelLevel then
   			   turtle.refuel(1)
   			   print("Refuel!")
		       end
end	   

local function dig()
               while turtle.detect()do
               turtle.dig()
               sleep(1)
               end 
end      

local function digUp()
			   while turtle.detectUp()do
      		         turtle.digUp()
      				 sleep(1)
			   end      
end

local function rotate()--rotate the turtle
			   turtle.turnRight()
			   turtle.turnRight()
end

local function forward() --move to turtle forward
			   while not turtle.forward() do
                         turtle.attack()
                         turtle.dig()
                         sleep(1)
			   end
end

local function path()--places a block under the turtle if their is none(creates path)
               while not turtle.detectDown()do
                         local slot = 
                         turtle.select(slot)
                         while not turtle.placeDown() do 
                                   slot = slot + 1
                                   if slot == 17 then
                                      print("Out of materials.please suppy more and press ENTER")
                                      while true do
                                            local e, k = os.pullEvent('key')
                                            if k == keys.enter then break end
                                      end      
                                      slot = 4
                                   end
                         end
               end
end               

local function placeChest()
               while turtle.getItemCount(chestSlot) ~= minChest do
                     print("No chest!")
                     sleep(10)
               end      
               turtle.select(chestSlot)
               turtle.placeUp()
               sleep(1)
end

local function emptyInv()
               for x = 3, 15 do
                   turtle.select(x)
                   turtle.dropUp()
               end
end

local function takeChest()--Picks up ender chest
               turtle.select(chestSlot)
               turtle.digUp()
               print("Got EnderChest!")
		       sleep(1)
end

local function checkInv()--check if inventory is full
        	   if turtle.getItemCount(16) ~= 0 then
   			      print("Inventory Full!")
   				  digUp()
   			      placeChest()
   				  emptyInv()
   				  takeChest()
			   end
end

local function mine()--mines a 3 by 3
               dig()
               forward()
               turtle.turnLeft()
               dig()
               rotate()
               dig()
               digUp()
               turtle.up()
               dig()
               rotate()
               dig()
               digUp()
               turtle.up()
               dig()
               rotate()
               dig()
               turtle.turnLeft()
               turtle.down()
               turtle.down()
end

local function placeTorch()--mines a 3 by 3 and places torch
               dig()
               forward()
               turtle.turnLeft()
               dig()
               rotate()
               dig()
               digUp()
               turtle.up()
               turtle.select(torchSlot)
               dig()
               turtle.place()
               rotate()
               dig()
               turtle.place()
               digUp()
               turtle.up()
               dig()
               rotate()
               dig()
               turtle.turnLeft()
               turtle.down()
               turtle.down()
end               



local function main()

for i = 1,miningLength do

    refuel()
    print("mining...")

    if i%torchInterval == 0 then
       placeTorch()
     else
       mine() 
    end

    path()
    checkInv()
end

rotate()

for i = 1,miningLength do
    forward()
end

placeChest()--Put Chest or EnderChest in chestSlot
emptyInv()

takeChest()--For EnderChest(delete if not using EnderChest)

turtle.turnLeft()
forward()

for i = 1,movingLength do

    refuel()
    mine()
	path()
	checkInv()                          
end

turtle.back()
turtle.turnLeft()
print("Ready to mine again.")
end

--Program!
for i = 1, noOfTunnel do
main()
end


Edit:What do you think of the code so far?
saikit555 #39
Posted 06 June 2013 - 11:58 AM
After using it a few time found something wrong with it. When the turtle is doing the mine function if something gets under it while it tries to do turtle.down if will get confuse and not know what to do. Any solution?

Edit: It also some times get stuck moving forward. I'm unsure why. Either its something wrong with the code or something to do with a weird bug i been getting where ocelot keep spawning everywhere all the time.

Edit: figured out the moving forward part. forgot to add more refuel commands when editing code.
theoriginalbit #40
Posted 06 June 2013 - 11:19 PM
Make sure you check fuel, make sure you allow for gravel/sand, make sure you check for mobs. An example with forward movement:


local function moveForward()
  --# keep trying to move forward until you can
  while not turtle.forward() do
    --# is a block in the way?
    if turtle.detect() then
      while turtle.detect() do
        turtle.dig()
        sleep(0.8) --# wait for sand/gravel to fall
      end
    --# out of fuel?
    elseif turtle.getFuelLevel() == 0 then
      --# refuel it in some manner
    --# a mob is in the way?
    elseif turtle.attack() then
      --# attack and kill the mob
      while turtle.attack() do end
    end
  end
end
saikit555 #41
Posted 07 June 2013 - 11:02 AM
Make sure you check fuel, make sure you allow for gravel/sand, make sure you check for mobs. An example with forward movement:
 local function moveForward() --# keep trying to move forward until you can while not turtle.forward() do --# is a block in the way? if turtle.detect() then while turtle.detect() do turtle.dig() sleep(0.8) --# wait for sand/gravel to fall end --# out of fuel? elseif turtle.getFuelLevel() == 0 then --# refuel it in some manner --# a mob is in the way? elseif turtle.attack() then --# attack and kill the mob while turtle.attack() do end end end end 
Yup. thanks. I do have that in the code.just forgot the fuel part. Btw would this work.

while not turtle.down() do --if something is under it stopping it from going down. it will keep trying until works?
               sleep(1)
end
theoriginalbit #42
Posted 07 June 2013 - 11:04 AM
Yup. thanks. I do have that in the code.just forgot the fuel part. Btw would this work.

while not turtle.down() do --if something is under it stopping it from going down. it will keep trying until works?
  sleep(1)
end
Only if it is a mob or falling block stopping it. if there is a block there then it will get stuck in that loop.
saikit555 #43
Posted 07 June 2013 - 01:45 PM
Could someone explain this:


 while true do
          local e, k = os.pullEvent('key')
          if k == keys.enter then break end
end      
theoriginalbit #44
Posted 07 June 2013 - 01:50 PM
that waits for the enter key to be pressed.

breakdown

--# infinitely loop
while true do
  --# wait here until a key is pressed
  local e, k = os.pullEvent("key")
  --# if the key that was pressed is the enter key, note that keys.enter is used, you could also put in the key code which is 28
  --# either way, its personal choice, imo keys.enter is easier to remember.
  if k == keys.enter then
	--# exit the current loop, i.e. the infinite loop
	break
  end
end