Reputation: 13
I am relatively new to coding on Lua but I have a little bit of experience in Python. I wanted to try something different where a random number would be rolled and you had to try and guess what the number would be. If you got it right the program would end and that would be it just something simple to work on in my free time. However, I ran into a problem with Lua where this if statement on Line 16 won't work.
print("Test")
print("--------------------------------------")
game = 1
x = math.random(1,6)
while game == 1 do
x = math.random(1,6)
io.write("Enter a number. If you roll that number on the dice you win: ")
user_input = io.read()
print(" ")
print("You chose " .. user_input)
print(" ")
print(x)
if user_input == x then -------------> this line doesn't work
print(" ")
print("You rolled the number you chose.")
game = 2
else
print(" ")
print("You did not roll the random number.")
print("--------------------------------------")
end
end
Upvotes: 1
Views: 131
Reputation: 4617
Replace if user_input == x then
with if tonumber( user_input ) == x then
. It ought to be obvious to you that user_input
is a string, and x
is a number; and there is no implicit type cast in Lua.
Bonuses:
f("a")
→ f'a'
,break
, getting rid of game
variable altogether (use while ( true )
),local
. In your example this applies to x
and user_input
and would apply to game
, were it not redundant, print(" ")
print("You did not roll the random number.")
print("--------------------------------------")
with
print [[
You did not roll the random number.
--------------------------------------
]]
Upvotes: 0
Reputation: 163
It appears that you are taking input from the console and storing it as a string. You currently are comparing a string to a integer. Which means that you will always end up in false. Here I changed your code to make it take input as a integer instead of a string so that the statement works now.
print("Test")
print("--------------------------------------")
game = 1
x = math.random(1,6)
while game == 1 do
x = math.random(1,6)
io.write("Enter a number. If you roll that number on the dice you win: ")
user_input = io.read("*number")
print(" ")
print("You chose " .. user_input)
print(" ")
print(x)
if user_input == x then
print(" ")
print("You rolled the number you chose.")
game = 2
else
print(" ")
print("You did not roll the random number.")
print("--------------------------------------")
end
end
Upvotes: 2