1

I'm having some trouble looping a piece of code.

I made a program where you have to insert a number and the PC computes some stuff.

My problem is that I'm not able to loop the if statement that prevents the user from typing a letter or something like that.

Here's the piece of code I need to loop:

-- first number
io.write("Tell me a number: ")
a = io.read("*number")
-- typing a letter
if a == nil
    then
        io.write("\n", "Sorry, this is an invalid imput.", "\n")
        io.write("\n", "Please tell me a number: ")
end

Could you please help me?

I've just started programming in Lua and I'm quite confused.

Thank you very much.

1 Answer 1

2

You are looking for a... ...well, loop:

local l = io.read("*line")
local a = tonumber(l)

while a == nil do
    print("sorry, invalid input")
    l = io.read("*line")
    a = tonumber(l)
end

(Side note: I don't speak lua, I've found the tonumber() function after 2 minutes of googling.)

4
  • Thank you very much! Actually, I've just started programming... from scratch. Thank you again and have a good day. :) Sep 8, 2013 at 10:30
  • 1
    As a side note @H2CO3 solution teaches you one more thing: when getting input from a user interactively you should read the input always as text (io.read("*line")), then process it to see if it matches your expectations and issue errors accordingly. io.read("*number") is used essentially when reading from files with known structure, i.e. when you know you will get a number. For this reason io.read("*number") is seldom used, since it reads from the standard input, which is usually the console unless some redirection at OS level has taken place. Sep 8, 2013 at 10:53
  • @LorenzoDonati Exactly. I've tried the above code with io.read("*number") but it didn't work. I assume that if it fails, it doesn't consume the characters to be read. Is that right?
    – user529758
    Sep 8, 2013 at 11:06
  • @H2CO3 it uses fscanf with a default format of "%lf" internally, see read_number function in the sources. Thus it has the same behavior as fscanf if a matching failure happens. Sep 8, 2013 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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