Comparison of numbers read with "io.read()" does not result in true as expected

Asked

Viewed 68 times

-2

I tried to put 1 and the second print was not. If I change x=io.read() for "x=1" it works normally

Follows the code

x = io.read()
if x ~= 0 then
    print(x.." diferente de 0")
end
if x == 1 then
    print(x.." igual a 1")
end

Example of input and output:

1
1 different than 0

  • 1

    Important you EDITAR this question, explaining it clearly, objectively and directly, emphasizing the difficulty found. Furthermore, provide us with a Example minimum, complete and verifiable problem, along with its attempt to resolve. What’s more, I suggest reading the Stack Overflow Survival Guide in English to better understand the functioning of the platform.

  • 1

    in lua when you give an io.read the input comes a string...so comparing it is "1" == 1, so it is false, to work out you could for example convert this io.read to integer with tonumber, ex : x = tonumber(io.read())

  • Welcome to [en.so]! You have posted an image of the code and/or error message. Although it sounds like a good idea, it’s not! One of the reasons is that if someone wants to answer the question, they can’t copy the code and change something inside. See more about this at this link - How NOT to ask questions manual

2 answers

4

Must be:

x = io.read()
if x ~= '0' then
    print (x .. ' deferente do 0')
end
if x == '1' then
    print (x .. ' igual a 1')
end

io.read() returns strings.

4

You are comparing text with number, so they are different values, so it is false and does not enter the if. That is correct:

x = io.read()
if x ~= 0 then
    print(x .. " diferente de 0")
end
if x == "1" then
    print(x .. " igual 1")
end
if tonumber(x) == 1 then
    print(x .. " igual 1")
end

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Either you compare text with text, or convert text to number to compare with number.

I didn’t get into the merit that the conversion could go wrong, and so it would need to be tested before using, so it might not be a good one used simply like this.

The first if gives true because "1" is different from 0, they are of different types, so do not even need to look at the value of each. This is the correct comparison.

Can read more about the function used that always returns string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.