Matteo Bini
Matteo Bini

Reputation: 65

Looping if statement in Lua

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.

Upvotes: 1

Views: 208

Answers (1)

user529758
user529758

Reputation:

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.)

Upvotes: 2

Related Questions