19

In my lua program, i want to stop and ask user for confirmation before proceeding with an operation. I'm not sure how to stop and wait for user input, how can it be done?

6 Answers 6

34
local answer
repeat
   io.write("continue with this operation (y/n)? ")
   io.flush()
   answer=io.read()
until answer=="y" or answer=="n"
2
  • Does io.read() impose automatic io.flush() when working with default stdin/out? Commented Jun 10, 2015 at 12:40
  • @EgorSkriptunoff, it might, but we can't be sure. I don't think ANSI C says anything about this.
    – lhf
    Commented Jun 10, 2015 at 12:47
15

Take a look at the io library, which by default has standard-input as the default input file:

http://www.lua.org/pil/21.1.html

10

I've worked with code like this. I will type this in a way it will work:

io.write("continue with this operation (y/n)?")
answer=io.read()
if answer=="y" then
   --(put what you want it to do if you say y here)
elseif answer=="n" then
   --(put what you want to happen if you say n)
end
0
0

I use:

     print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
    (Insert stuff here)
elseif re == "n" or "N" then
    print("Ok...")
end
1
  • 1
    The conditionals there are wrong, eg re == "y" or "Y" should be re == "y" or re == "Y". It's probably good to be aware that we can check re:lower() == "y" too.
    – PaulR
    Commented Sep 23, 2018 at 14:45
0

try to use folowing code

m=io.read() if m=="yes" then (insert functions here) end

-2
print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
    (Insert stuff here)
elseif re == "n" or "N" then
    print("Ok...")
end

From the bit of lua that I've done (not a lot), I'm going to say that using both uppercase and lowercase letters is redundant if you use string.sub.

print("Continue? (y/n)")
local re = io.read()

--[[Can you get string.sub from a local var? 
If so, this works. I'm unfamiliar with io(game 
lua uses GUI elements and keypresses in place of the CLI.]]

if re.sub == "y" then
    --do stuff
if re.sub == "n" then
    --do other stuff
end

That should work.

1
  • 2
    re.sub will resolve to the function string.sub & always be unequal to "y" or "n". Besides, string matching is case sensitive. At best you can do re:match("[nN]") and re:match("[yY]") Commented Jan 14, 2018 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.