You could try something like this:
-- Seed the random number generator with the current time
-- so the number chosen is not the same every time
math.randomseed(os.time())
rad = math.random(100)
--print("rad = " .. rad)
print("Do you want to play a game?")
playerInput = io.read()
if playerInput == "yes" then
repeat
print("What is your number?")
numGuess = tonumber(io.read())
if numGuess < rad then
print("Too low")
elseif numGuess > rad then
print("Too high")
else
print("You got the number")
end
until numGuess == rad
else
print("You scared?")
end
I added seeding the random number generator, otherwise the number chosen was always 0 for me. I also rearranged your loop a bit to avoid duplication.
I think the main problem you were having is comparing a number to a string, to avoid that I converted the value read to a number using the tonumber
function. This will still crash if anything but a number is input so in a real program you'd want to add some error checking.
Here's a version using the while loop rather than repeat and io.read('*n')
rather than tonumber()
. I moved the prompt to the top of the loop so the body executes after you guess the right number, otherwise the loop would just exit without printing anything because the loop condition was no longer true.
math.randomseed(os.time())
print("Do you want to play a game?")
playerInput = io.read()
if playerInput == "yes" then
local numGuess = 999
local rad = math.random(0,100)
while numGuess ~= rad do
print("What is your number?")
numGuess = io.read('*n')
if numGuess < rad then
print("To low")
elseif numGuess > rad then
print("to high")
else
print("You got the number")
end
end
else
print("You scared?")
end