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

This work but this doesn't, if statements

Started by makromoo, 10 January 2015 - 12:53 PM
makromoo #1
Posted 10 January 2015 - 01:53 PM
I'm a bit baffled..

name = "john"


This doesn't work as it should
if (name ~= "john" or name ~= "sam") then
print("Access denied")
else
print("Welcome")
end

Yet this does
if (not name == "john" or not name == "sam") then
print("Access denied")
else
print("Welcome")
end
Edited on 10 January 2015 - 01:08 PM
Lignum #2
Posted 10 January 2015 - 02:24 PM
The second one doesn't work.

not name == "john"
is parsed as

(not name) == "john"

not name will always be false as long as it's not nil, which it isn't. So you will end up with false == "john", which is false.

Anyway, this is what you're supposed to do:

if name ~= "john" and name ~= "sam" then
   --# Access denied...
else
   --# Access granted...
end

After all, we want to deny access when the name isn't john and when it isn't sam.

Also, please don't use globals unless you have to. Once you create a global, it can be accessed from everywhere on the computer, even after the program is finished.
See for yourself, make a new file:

myVariable = 6

Run it, then start the Lua console and type "myVariable" (no quotes). You can imagine why this would be a problem…
So do this instead:

local name = "john"
makromoo #3
Posted 10 January 2015 - 02:54 PM
That was quick! :P/>

Ah sorry I didn't use the code I tested it with, trusted my memory too much :P/>

Thanks for the solution and for explaining why 'or' wouldn't work and 'and' will :)/>
Also thanks for the tip about global variables, I really didn't know that, might explain why in previous times computer needed a reboot for program to properly work.

Thank You, Lignum! :)/>
Lignum #4
Posted 10 January 2015 - 04:52 PM
You're welcome!