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

Multiple if then statements

Started by GrayTheWolf, 06 March 2014 - 01:57 AM
GrayTheWolf #1
Posted 06 March 2014 - 02:57 AM
I want to make this so that it will send the respective rednet broadcasts, and that works. I also want it to say "Invalid Floor!" for any number other and 1,2, and 3.


rednet.open("back")
while true do
term.clear()
term.setCursorPos(1, 1)
print("Enter Desired Floor #:")
input = read()
if input == "1" then
rednet.broadcast("1")
if input == "2" then
rednet.broadcast("2")
if input == "3" then
rednet.broadcast("3")
else print("Invalid Floor!")
  sleep(3)
end
end

Right now it just gives me a bunch of errors about expecting end in places to close the while true statement.
How can I make this work?
Lyqyd #2
Posted 06 March 2014 - 04:53 AM
You should be using elseif instead of if for options 2 and 3.
manu3d #3
Posted 06 March 2014 - 08:59 PM
Lua syntax for the a simple if/then control structure is this:


if(condition)then
    doSomething()
end

You code lacks the "end" keyword to close each if/then structure. This is why you get the errors.

[EDITED]
However, it is correct to do as lyqyd suggests, so that you have if-then / elseif-then / elseif-then / else. Otherwise your else block at the end will also catch the cases where input=1 and input=2, which is probably not what you want.
Edited on 08 March 2014 - 09:43 AM
Lyqyd #4
Posted 06 March 2014 - 10:02 PM
Using elseif instead of more if blocks also allows the final else to behave as expected.
manu3d #5
Posted 08 March 2014 - 10:40 AM
Good point. With the original example an input value of 1 would trigger both the first if/then AND the else in the last if/then/else. Doh! My bad. Edited my first post to reflect this.
Edited on 08 March 2014 - 09:44 AM