[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: io.read() not excecuting
- From: Dirk Laurie <dirk.laurie@...>
- Date: Sat, 13 Feb 2016 17:21:41 +0200
2016-02-13 12:55 GMT+02:00 Richard Gelling <blackheart40@gmail.com>:
> 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!
The first read statement reads only a number. It stops as soon
as going on does not conform to number syntax. In particular,
it does not read the end-of-line character which you had to
hit to finish the input.
The second read statement reads a whole line, starting at the
current position. That's just the rest of the first statement, which
is empty.
You can see more clearly what happens as follows:
$ lua blackheart.lua
Enter a number: 10y
3628800
Do you want to enter another number? (y/n)
Enter a number: 15y
1307674368000
Do you want to enter another number? (y/n)
Enter a number: