[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: io.read() not excecuting
- From: Nagaev Boris <bnagaev@...>
- Date: Sat, 13 Feb 2016 14:26:47 +0300
On Sat, Feb 13, 2016 at 1:55 PM, Richard Gelling <blackheart40@gmail.com> wrote:
> Hi
> I am just starting to learn Lua but have run in to something which I can’t seem to figure out. In messing around with an example from a book I have wrote the following code:
>
> function fact(n)
> if n==0 then
> return 1
> else
> if n < 0 then
> return n * fact(n+1)
> elseif n > 0 then
> return n * fact(n-1)
> else
> return nil
> end
> end
> end
>
> continue = true
>
> while continue == true do
> io.write("Enter a number: ")
> a = io.read("*n") -- reads a number ( this works fine )
> print(fact(a))
> print("Do you want to enter another number? (y/n) ")
> response = io.read() - - this never executes
>
> if response == "y" then
> continue = true
> else
> continue = false
> end
>
> end
>
> I think I might have altered something which stops the second io.read() , response = io.read(),from being executed and the program just finishes without allowing the user to input a response.
>
> It has worked in that it has gone as far as allowing input, but would not recognise ‘y’ of ’n’ as when watching the variable when you type in ‘y’ or ’n’ the variable actually has ‘\ny’ or ‘\nn’ stored in it. Any help would be greatly appreciated as I seem to have run into a brick wall!
>
> Thanks for any help
>
> Richard Gelling
Hi,
I don't know why exactly it doesn't work. Maybe "new line" character
is consumed not by io.read("*n"), but by io.read(), so the latter
considers the line to be empty.
I found the following work around for this. Replace io.read("*n") with
tonumber(io.read()).
--
Best regards,
Boris Nagaev