如果声明不适用于Lua for io.read

时间:2013-05-18 07:30:51

标签: lua

我正在尝试制作一个'简单'的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())

2 个答案:

答案 0 :(得分: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时,您需要将循环设置为"y" or "Y" or "n" or "N",否则循环将继续。
  4. 第四,在循环中将循环设置为true是不必要的,它以true开头,您可以做的唯一更改是将其设置为false。并且由于每个条件是相互排斥的,即输入"y" or "Y"互为排他性,输入为"n" or "N" "y" or "Y""n" or "N"。除非您希望循环结束,否则您无需担心它被设置为false。

答案 1 :(得分: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())