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

[LUA] Then expected. Is this function messed up?

Started by sixalpha, 25 January 2013 - 02:36 PM
sixalpha #1
Posted 25 January 2013 - 03:36 PM

function updateDir(turn)
if turn == "right" and dir = "N" then
  dir = "E"
end
if turn == "right" and dir = "E" then
  dir = "S"
end
if turn == "right" and dir = "S" then
  dir = "W"
end
if turn == "right" and dir = "W" then
  dir = "N"
end
if turn == "left" and dir = "N" then
  dir = "W"
end
if turn == "left" and dir = "W" then
  dir = "S"
end
if turn == "left" and dir = "S" then
  dir = "E"
end
if turn == "left" and dir = "E" then
  dir = "N"
end
end
Orwell #2
Posted 25 January 2013 - 03:51 PM
You have 'and dir = "x" then' everywhere instead of 'and dir=="x" then' with the double equal signs. Also, look into using elseif statements. Here is your code using elseif and the equal signs:

function updateDir(turn)
  if turn == "right" and dir == "N" then
	dir = "E"
  elseif turn == "right" and dir == "E" then
	dir = "S"
  elseif turn == "right" and dir == "S" then
	dir = "W"
  elseif turn == "right" and dir == "W" then
	dir = "N"
  elseif turn == "left" and dir == "N" then
	dir = "W"
  elseif turn == "left" and dir == "W" then
	dir = "S"
  elseif turn == "left" and dir == "S" then
	dir = "E"
  elseif turn == "left" and dir == "E" then
	dir = "N"
  end
end

Also, whatever you're trying to do, I bet you can do it in an easier way. :P/> For example, use a number from 0 to 3 to represent the direction. Then you'd have:

function updateDir(turn)
  local sign = (turn == "right") and 1 or -1
  dir = (dir+sign)%4
end

You can always get a string to print the direction like this:

local directions = {"EAST","SOUTH","WEST","NORTH"}
print( directions[dir+1] )
sixalpha #3
Posted 25 January 2013 - 06:42 PM
Oh what a silly mistake, and I looked at this for awhile trying to figure it out. Thank you kind sir!