2

我正在尝试做一个“简单”的 Y/N 答案选择。(你一直在旧程序上看到)但是我正在使用的 If 语句似乎不想工作。我什至打印出变量,它与我想要比较的结果相去甚远,但它仍然通过它。

        --Porgram Functions

        function check()

        --Local Variables
            local num = 0
            local loop = true
            io.write("Continue? (Y/N):")
            --User input
            local input = io.read()

            while(loop==true) do

                if (input=="y" or "Y") then

                    print("Ok!")
                    loop = true
                    num = 1

                elseif (input=="n" or "N") then

                    print("Fine...")
                    num = 2

                else

                    print("Invalid Answser!")
                    loop = true
                    num = 0

                end
            end
            print(input)
            return(num)
        end

        print (check())
4

2 回答 2

3

我会这样写你的函数:

function check()
    io.write("Continue? (Y/N): ")
    answer = io.read()
    while( not (answer == "Y" or answer == "N") ) do
        io.write("Invalid Answer! Try again (Y/N): ")
        answer = io.read()
    end
    if answer == "Y" then
        print("Ok!")
        return 1
    else
        print("Fine...")
        return 2
    end
end

print(check())

它的一些使用示例:

Continue? (Y/N): Huh?
Invalid Answer! Try again (Y/N): N
Fine...
2
>Exit code: 0
>lua -e "io.stdout:setvbuf 'no'" "a.lua" 
Continue? (Y/N): Huh?
Invalid Answer! Try again (Y/N): Y
Ok!
1

您的代码的工作版本将是:

function check()
    local num = 0
    local loop = true    
    io.write("Continue? (Y/N):")

    while(loop==true) do    
        --User input
        local input = io.read()   
        if (input == "y" or  input == "Y") then    
            print("Ok!")
            num = 1
            loop = false --we want to stop looping if input is valid      
        elseif (input == "n" or input == "N") then    
            print("Fine...")
            num = 2
            loop = false --we want to stop looping if input is valid   
        else
            print("Invalid Answser!")
            -- loop = true no need to set looping to true again
            num = 0    
        end
    end
    return(num)
end

所做的更改是:

  1. while循环中获取用户输入,这样如果输入无效并且循环再次使用获取输入背后的相同逻辑,我们不必编写两种获取输入的情况;一个在循环外,另一个在循环内。当循环再次开始时,它也会暂停执行,这就是产生所有输出的原因!
  2. input == "y" or "Y"不按你的想法做。相反,它评估为(input == "y") or ("Y")您想要input == "y" or input == "Y"的。
  3. 您需要将循环设置false为输入为 either 时"y" or "Y" or "n" or "N",否则循环将继续。
  4. 第四,将循环设置为循环true内部是不必要的,它以 开头true,您可以做的唯一更改是将其设置为false。并且由于每个条件都是互斥的,即 input"y" or "Y"与 input 互斥,"n" or "N"或者它既不是 "y" or "Y"or "n" or "N"。除非您希望循环结束,否则您无需担心它被设置为 false。
于 2013-05-18T07:39:04.530 回答
1
local function check()
   io.write"Continue? (Y/N): "
   local ans, num = {y = 1, n = 2}
   repeat
      num = ans[io.read():lower()] or 3
      io.write(({"Ok!\n","Fine...\n","Invalid Answer! Try again (Y/N): "})[num])
   until num < 3
   return num
end

print (check())
于 2013-05-18T08:09:30.627 回答