The method io.read()
returns a string
(character string).
You are comparing this string to the number 18. You cannot mix the two types (string with number) in the comparisons.
To convert a string
in number there is the function tonumber(string)
.
Example of use:
print("Qual é a sua idade")
idadetexto = io.read()
idadenumero = tonumber(idadetexto)
if idadenumero < 18 then
print("Você é menor de idade")
else
print("Você é maior de idade")
end
Note that you could have just done it idade = tonumber(idade)
, but I preferred to use variables of different names to facilitate the visualization.
As Mr @Francisco said in his comments, it is worth noting that if the tonumber
not being able to convert, returns nil
(which is the null value, not a string "nil"
). You may need to test the return depending on the application.
To test whether you returned a nil
you use if variavel == nil
, quote-free.
missed
idade = tonumber(idade)
– Bacco
Okay, I’ll test it :)
– Rogério Matheus
It worked, thank you very much !!!
– Rogério Matheus