lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

2016-02-13 12:55 GMT+02:00 Richard Gelling <>:

> 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 ="*n")     -- reads a number ( this works fine )
>   print(fact(a))
>   print("Do you want to enter another number? (y/n) ")
>   response =          - - 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 , response =,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
Do you want to enter another number? (y/n)
Enter a number: 15y
Do you want to enter another number? (y/n)
Enter a number: