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

[LUA] If not , not working?

Started by Ermans, 11 February 2013 - 05:40 AM
Ermans #1
Posted 11 February 2013 - 06:40 AM
I have created a simple programs:

write("")
string1 = read()
string1 = tonumber(string1)

if not string1 == nil then
print("It's a number!")
else
print("Isn't a number")
end


But if I write 3 the result is "isn't a number"

I have saw that the problem is "not" because if I running this programs work fine:

write("")
string1 = read()
string1 = tonumber(string1)

if string1 == nil then
print("Isn't a number")
else
print("It's a number!")
end
Why?


Or, there is another way to obtain the same output of "if not" ?
tesla1889 #2
Posted 11 February 2013 - 06:44 AM
try

if not string1 then

nil -> false when cast to boolean

EDIT: why would you

write("")
?

that doesn't do anything

if you want to move to the next line:

print()
Lyqyd #3
Posted 11 February 2013 - 06:57 AM
To explain the above better, applying a boolean not operation to either false or nil values will result in true, and any other values will result in false. So if it is nil, `not string1` will result in true, satisfying the conditional.

You could also use the inequality comparison, if you needed to check specifically that it is not nil (but you don't mind it being false):


if string1 ~= nil then