Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement in Lua

Tags:

lua

i'm trying to do simplest of things:

  • program prints first message and waits for user input
  • user types in "play" or "leave"
  • if user types in "play" program prints "let's play" and exits (for now)
  • if user types in "leave" program prints "bye" and exits
  • if user types in something different than "play" or "leave" program prints first message and waits for user input again

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


1 Answers

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.

like image 170
luther Avatar answered Sep 19 '26 11:09

luther