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

Program seemingly ignoring "if" statements, and running all code?

Started by Cainite, 30 July 2014 - 02:37 AM
Cainite #1
Posted 30 July 2014 - 04:37 AM
Edit: SOLVED. Thanks to hilburn.

I'm a beginner using this mod to teach myself the basics of programming. After getting a decent, but inefficiently written Tree Farm program working, I decided to try writing something similar to the default "go" program (in terms of what it does, not how it's written) to make it a bit more efficient. Here's my code (in a turtle):

Spoiler

local function Move(direction, amount)

  if direction == up then
	for i = 1, amount do
	  turtle.up()
	end
  end

  if direction == down then
	for i = 1, amount do
	  turtle.down()
	end
  end

  if direction == forward then
	for i = 1, amount do
	  turtle.forward()
	end
  end

  if direction == back then
	for i = 1, amount do
	  turtle.back()
	end
  end

  if direction == left then
	for i = 1, amount do
	  turtle.turnLeft()
	end
  end

  if direction == right then
	for i = 1, amount do
	  turtle.turnRight()
	end
  end

end


-- testing
Move(left, 2)

Fairly self-explanatory what it's supposed to do. Put in a movement direction/type, and amount of times to do that movement, then it does that movement type that number to times.

The problem: It's cycling through all movement types. As in it goes, Up 2, Down 2, Forward 2, Back 2, Turn Left 2, Turn Right 2.

Obviously, I'm doing something wrong, but I have no idea what. It works fine if I only write the "up" and "down" sections, which is even more confusing to me.

Sorry if my format/layout isn't ideal either, kind of just making that up as I go.
Edited on 30 July 2014 - 08:43 AM
hilburn #2
Posted 30 July 2014 - 10:16 AM
Problem is quite simple, for strings, that is words, sentences, basically anything that isn't a number, you need to let LUA know that it is a string by surrounding it with quotation marks ("). Without this, LUA reads it as a variable name, so basically what is happening is that you are passing an empty (or nil) variable to the function and then testing it against 6 other nil variables, so they all return true.

Add in the quotation marks and you'll be golden.
Cainite #3
Posted 30 July 2014 - 10:35 AM
Well, I feel like a dumbass, I should have noticed that. I even did it the right way in my previous program.
Thank you for pointing out my shame your help!

Is there a way to mark this thread as solved or something? I'll just add that to the top of the op for now.
Edited on 30 July 2014 - 08:43 AM
hilburn #4
Posted 30 July 2014 - 02:18 PM
Haha, on my phone, unless it's in code tags I don't argue with it