What is wrong with my code? this is a really easy fix I bet but I am pretty new to Lua so I cannot figure it out. The code is a random number generator that you are supposed to guess the number (its obviously not done) but it says "Lua: main.lua:8: attempt to compare string with number" here is the code
local number2 = math.random(1,100)
local hi=2
repeat
print("pick a number, 1-100")
local number = io.read ()
if number == number2 then print("you got it!! congrats")
end
if number <= number2 then print("too high!")
end
if number >= number2 then print ("too low!")
end
until (hi)==2
The problem is that io.read()
returns a string - the next line of stdin, typically the user's input - rather than a number. Testing a string against a number - or any two values of different types - for equality in Lua always yields false
. Thus number == number2
will always be false
and you'll fall through to number <= number2
. This raises the exception you're seeing; <=
is well defined for two numbers or two strings, but not for a number and a string (should it compare lexicographically or numerically?), so Lua does the sensible thing and throw an error.
The fix is simple: You have to convert the user's input using tonumber
or read a number. You can do the latter using io.read("*n")
. It is possible that io.read("*n")
returns with nil
if the input was invalid, so we have to handle that.
Here's the fixed code:
local secret_number = math.random(1, 100)
repeat
print("pick a number, 1-100")
local guess_number = io.read("*n")
if not guess_number then print("invalid input!")
elseif guess_number < secret_number then print("too low!")
elseif guess_number > secret_number then print("too high!") end
until guess_number == secret_number
print("you got it!! congrats")
Note that since you were not setting hi
, the loop would have continued forever, rather than only exiting after the number has been guessed. Also, your "too low" and "too high" messages were swapped.