Reputation:
i'm trying to do simplest of things:
however current code just prints first message 2 times and exits:
print("welcome. you have 2 options: play or leave. choose.")
input = io.read()
if input == "play" then
print("let's play")
end
if input == "leave" then
print("bye")
end
if input ~= "play" or "leave" then
print("welcome. you have 2 options: play or leave. choose.")
end
what is wrong here? any help appreciated, thanks
Upvotes: 3
Views: 2238
Reputation: 11
You need a loop, as you can see this while here is saying, if the input isn't exit, redo the code, and the else means that it will check for the if, the elseif, then finally, the else.
print("welcome. you have 2 options: play or leave. choose.")
while input ~= "exit" do
input = io.read()
if input == "play" then
print("let's play")
elseif input == "leave" then
print("bye")
else
print("welcome. you have 2 options: play or leave. choose.")
end
end
Upvotes: 1
Reputation: 72422
The usual idiom is
if input == "play" then
print("let's play")
elseif input == "leave" then
print("bye")
else
print("welcome. you have 2 options: play or leave. choose.")
end
but you probably need a loop as suggested by @luther.
Upvotes: 0
Reputation: 5564
An if
statement will only execute once. It doesn't jump to other parts of the program. To do that you need to wrap your input code in a while
loop and break out when you get a valid response:
while true do
print("welcome. you have 2 options: play or leave. choose.")
local input = io.read()
if input == "play" then
print("let's play")
break
elseif input == "leave" then
print("bye")
break
end
end
Read more about loops here.
Upvotes: 4
Reputation: 26385
The line if input ~= "play" or "leave" then
is evaluated as:
if (input ~= "play") or "leave" then
The string "leave"
, or any string for that matter, is considered a truthy value.
You need to compare both strings, using and
:
if input ~= "play" and input ~= "leave" then
print("welcome. you have 2 options: play or leave. choose.")
end
Upvotes: 1