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

Help with Turtle direction

Started by 25FiveDelta, 20 January 2014 - 10:11 PM
25FiveDelta #1
Posted 20 January 2014 - 11:11 PM
Following youtube tutorial for learning CC by BSGSamuel

I decided to use "if" statements in stead of the % used by the tutor.

My question is how to get the index/key of the orientations{} table and pass back to the variable "orientation"

For example if the program finished and the turtle is oriented to the South, I want assign 3 the "orientation" variable. So that the next time I rerun the code, the turtle knows it is facing South? hope my question is clear.




orientation = 1

orientations ={"North", "East", "South", "West"}

function checkForO()

   if orientation>4 then
	 orientation = 1
   end

  if orientation<1 then
	orientation = 4
  end

end

function left()

   turtle.turnLeft()
   orientation = orientation - 1
   checkForO()

end

function right()

   turtle.turnRight()
   orientation = orientation + 1
   checkForO()

end

for i = 1, 5 do

   left()
   print("I am facing " .. orientations[orientation])

end

--for i = 1, 3 do

   --right()
   --checkFor0()
   --print("I am facing "..orientations[orientation])

--end
Bomb Bloke #2
Posted 21 January 2014 - 02:44 AM
So you're saying that you want the turtle to automatically recall which way it was facing when the script was last used?

How you would do this depends on whether or not you want it to work if the turtle's rebooted.

I suspect you're better off setting up a GPS system so that the turtle can determine its facing on its own, which would allow it to function correctly even if you pick the turtle up and place it down a different way yourself.
25FiveDelta #3
Posted 21 January 2014 - 09:42 AM
Thanks for the reply.
I guess have to learn a little bit more. correct me if I am wrong, I just realized that the file need to be open and have the the variable updated after at the end of the program execution. before it can remember the direction it is facing.

But still how do you retrieve the index value of an item in a table?
CometWolf #4
Posted 21 January 2014 - 11:34 AM
You can use the pairs iterator in a for loop to get the indexes of a table

local tTable = {[5] = "test",["derpderp"] = "derp"}
for k,v in pairs(tTable) do
  print(k.." = "..v) --here k represents the index, and v is the variable it holds.
end
This will print
5 = test
derpderp = derp

read more here:
http://www.lua.org/pil/4.3.5.html
Edited on 21 January 2014 - 11:43 AM
Lyqyd #5
Posted 21 January 2014 - 12:17 PM
In that table declaration, the 5 should be [5].
CometWolf #6
Posted 21 January 2014 - 12:43 PM
Right ofcourse, fixed :)/>