"Attempt to compare string with number" when comparing in Lua

Asked

Viewed 49 times

3

print("Qual é a sua idade")
idade = io.read()

if idade < 18 then
   print("Você é menor de idade")
else
  print("Você é maior de idade")
end

He always makes that mistake :

lua: aula05_parte4.lua:4: attempt to compare string with number
stack traceback:
aula05_parte4.lua:4: in main chunk
[C]: in ?

What can I do?

  • 2

    missed idade = tonumber(idade)

  • Okay, I’ll test it :)

  • It worked, thank you very much !!!

1 answer

4

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.

  • Okay, thank you very much :)

  • important to remember that tonumber returns nil if it cannot convert the input

  • @Francis added his remark.

Browser other questions tagged

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