【问题标题】:Lua - get command line input from user?Lua - 从用户那里获取命令行输入?
【发布时间】:2013-12-28 11:12:34
【问题描述】:

在我的 lua 程序中,我想在继续操作之前停止并要求用户确认。我不确定如何停止并等待用户输入,该怎么做?

【问题讨论】:

    标签: lua user-input blocking wait


    【解决方案1】:
    local answer
    repeat
       io.write("continue with this operation (y/n)? ")
       io.flush()
       answer=io.read()
    until answer=="y" or answer=="n"
    

    【讨论】:

    • 在使用默认标准输入/输出时,io.read() 是否会自动强制 io.flush()?
    • @EgorSkriptunoff,可能,但我们不能确定。我不认为 ANSI C 对此有任何说明。
    【解决方案2】:

    查看io 库,默认情况下,它具有标准输入作为默认输入文件:

    http://www.lua.org/pil/21.1.html

    【讨论】:

      【解决方案3】:

      我使用过这样的代码。我将以一种可行的方式输入:

      io.write("continue with this operation (y/n)?")
      answer=io.read()
      if answer=="y" then
         --(put what you want it to do if you say y here)
      elseif answer=="n" then
         --(put what you want to happen if you say n)
      end
      

      【讨论】:

        【解决方案4】:

        我用:

             print("Continue (y/n)?")
        re = io.read()
        if re == "y" or "Y" then
            (Insert stuff here)
        elseif re == "n" or "N" then
            print("Ok...")
        end
        

        【讨论】:

        • 条件句有错误,例如re == "y" or "Y"应该是re == "y" or re == "Y"。很高兴知道我们也可以检查re:lower() == "y"。
        【解决方案5】:

        尝试使用以下代码

        m=io.read() if m=="yes" then (insert functions here) end

        【讨论】:

          【解决方案6】:
          print("Continue (y/n)?")
          re = io.read()
          if re == "y" or "Y" then
              (Insert stuff here)
          elseif re == "n" or "N" then
              print("Ok...")
          end
          

          从我做过的一些 lua 中(不是很多),我要说的是,如果你使用 string.sub,同时使用大写和小写字母是多余的。

          print("Continue? (y/n)")
          local re = io.read()
          
          --[[Can you get string.sub from a local var? 
          If so, this works. I'm unfamiliar with io(game 
          lua uses GUI elements and keypresses in place of the CLI.]]
          
          if re.sub == "y" then
              --do stuff
          if re.sub == "n" then
              --do other stuff
          end
          

          应该可以的。

          【讨论】:

          • re.sub 将解析为函数 string.sub 并且始终不等于 "y" 或 "n"。此外,字符串匹配区分大小写。充其量你可以做到re:match("[nN]")和re:match("[yY]")
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-04-11
          • 2021-07-28
          • 1970-01-01
          • 2019-06-19
          • 1970-01-01
          • 2013-09-03
          • 1970-01-01
          相关资源
          最近更新 更多