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.

4

1 回答 1

2

您正在寻找... ...嗯,循环:

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

(旁注:我不会说 lua,我在tonumber()谷歌搜索 2 分钟后找到了这个功能。)

于 2013-09-08T10:22:11.683 回答