如何在输入错误类型后将“io.read”两次作用于一个变量上?

嗨,我对Lua相当新(虽然我用Java编码),所以我对此一无所知。我基本上在试图获取用户的输入,如果它不是正确的类型,那么重新开始。现在,我不确定是Lua还是我的IDE(如果有用我的ZeroBrane Studio),但出于某种原因它不会重新输入。(它只是循环,这意味着它跳过了io.read行)

:: restart ::
...
a = io.read"*number"if unit == nil then
  print"错误!不正确的输入!\n重新启动..."goto restart
end

哦,是的,我在使用restart的goto命令。我认为那可能是导致问题的原因,但我也尝试过这个:

a = io.read"*number"--输入非数字
打印(a)--打印
a = io.read"*number"--跳过
打印(a)--打印

当您输入数字时,它不会跳过。

任何帮助都会很好。提前感谢。

点赞
用户4273199
用户4273199

相较于使用内置的 io.read() 过滤器(我认为有时候会有 bug),你应该考虑使用一个自己的小函数来保证用户提供正确的数据。

这是这样的一个函数:

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 被认为是不好的编程实践。

2019-02-15 07:28:55
用户6834680
用户6834680
::restart::
    local a = io.read("*n", "*l")
    if a == nil then
        io.read("*l") -- 跳过错误的输入行
        print("错误!输入不正确!\n重新开始...")
        goto restart
    end

注:如有需要,使用 goto 可以使代码更易懂。例如,在这段代码中使用 whilerepeat-until 循环并不会使其更好(你需要额外的本地变量或 break 语句)。

2019-02-15 07:47:28
用户4972062
用户4972062
local a
repeat
  a = io.read()
  a = tonumber(a)
  if not a then
    print("输入不正确!\n(请只输入数字)")
  end
until a
2019-02-16 22:57:03