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

If statement using OR's

Started by Uch1ha_Sasuke, 02 December 2013 - 05:42 PM
Uch1ha_Sasuke #1
Posted 02 December 2013 - 06:42 PM
I have an advanced computer with a wireless modem on the right.

My program :
==============================================================================

rednet.open("right")
local modem = peripheral.wrap("right")
text = io.read()

==============================================================================
Then it needs to check if the input was a "1" or "2" or "3" or "4" using a if statement i am using this which does not work :
==============================================================================

if text ~= "1" or "2" or "3" or "4" then
print("Incorrect Data")
end

==============================================================================

Need some help figuring this out
Thank You in advance!
Okyloky9 #2
Posted 02 December 2013 - 06:47 PM
<code>
if text == "1" then
– whatever
elseif text == "2" then
–whatever
elseif text == "3" then
–whatever
elseif text == "4" then
–whatever
else
– do something different than if it gets a 1-4 value
end
</code>

This is just how I've done it before, there is probably a quicker/simpler method.
theoriginalbit #3
Posted 02 December 2013 - 06:50 PM
This is because of how Lua works. Firstly, in Lua false and nil both resolve to false when present in conditionals, anything else resolves to true meaning that this will never be false

if "1" then
  print("This is always print")
else
  print("This will never be seen")
end

So knowing this, you should be able to notice that your if statement becomes

if text ~= "1" or true or true or true then

this means that you need to check the text against EACH variable you wish it to be!

if text ~= "1" or text ~= "2" or text ~= "3" or text ~= "4" then

now sometimes this could be annoying to do, especially if you have lots of numbers, in this case you should convert the string to a number and just perform a range check

text = tonumber(text) --# convert it to a number
if text and text >= 1 and text <= 4 then
  print("this is valid")
elseif not text then
  print("They didn't enter a number!")
else
  print("it is a number, but its not one we want")
end