Heyo。我对Lua还是很陌生(尽管我使用Java编写代码),所以我对此一无所知。我基本上是在尝试获取用户的输入,如果输入的类型不正确,请重新启动。现在,我不确定是Lua还是我的IDE(如果有帮助,我正在使用ZeroBrane Studio),但是由于任何原因它都不会重新输入。 (它只是循环,这意味着它会跳过io.read行)
::restart::
...
a = io.read("*number")
if unit == nil then
print("Error! Incorrect Input!\nRestarting...")
goto restart
end
哦,是的,我正在使用goto命令重新启动。我以为这可能是造成此问题的原因,但我也尝试过这样做:
a = io.read("*number") --input non-number
print(a) --prints
a = io.read("*number") --skips
print(a) --prints
输入数字时,它不会跳过。
任何帮助都会很好。预先感谢。
答案 0 :(得分:1)
我自己解决了nvm
local a
repeat
a = io.read(); a = tonumber(a)
if not a then
print("Incorrect Input!\n(Try using only numbers)")
end
until a
答案 1 :(得分:0)
::restart::
local a = io.read("*n", "*l")
if a == nil then
io.read("*l") -- skip the erroneous input line
print("Error! Incorrect Input!\nRestarting...")
goto restart
end
P.S。
随时使用goto
可以使您的代码更易于理解。
例如,在此代码中使用while
的{{1}}循环不会更好(您需要其他局部变量或repeat-until
语句)。
答案 2 :(得分:-1)
您应该考虑使用自己的小函数来确保用户将提供正确的数据,而不是使用io.read()
的内置过滤器(我确实认为有时会出现问题)。
这是一个功能:
function --[[ any ]] GetUserInput(--[[ string ]] expectedType, --[[ string ]] errorText)
local --[[ bool ]] needInput = true
local --[[ any ]] input = nil
while needInput do
input = GetData()
if ( type(input) == expectedType ) then
needInput = false
else
print(errorText)
end
end
return input
end
然后您可以通过以下方式调用它:
local userInput = GetUserInput("number", "Error: Incorrect Input! Please give a number.")
哦,还有一个旁注:Goto被认为是不好的做法。