在Lua中使用if,elseif和else重复直到循环

时间:2013-12-01 21:26:11

标签: lua string-comparison

我是Lua的新手,我遇到了这段代码的问题。它应该使用io.read验证用户输入,然后运行正确的ifelseifelse语句。一旦用户输入正确的响应,代码就应该结束。出于某种原因,代码只会运行初始if语句。任何帮助将不胜感激。

repeat
    resp1 = io.read()

    if resp1 == "Yes" or "yes" then
        print("Well alright then, come on in.")
        print("Let me just take your blood sample like all the rest and you'll be good to go.")
    elseif resp1 == "No" or "no" then
        print("Oh, your not? Then why are you up here?")
        print("Oh nevermind then. None of my business anyways. All I'm supposed to do is take a blood sample for everyone who enters the town.")
        print("So let us get that over with now, shall we?")
    else
        print("Please respond with Yes or No")
    end
until resp1 == "Yes" or resp1 == "No" or resp1 == "no" or resp1 == "yes"

2 个答案:

答案 0 :(得分:4)

你的问题在于这一行:

if resp1 == "Yes" or "yes" then

这是两个单独的表达式,在Lua中,除nilfalse之外的所有内容都是真值,因此它会选择要运行的if语句,因为Lua中的字符串,即使是空的,就条件而言,评估为true。如果它有助于你理解,可以这样想:

if (resp1 == "Yes") or ("yes") then

如果你真的想将resp1与两个值进行比较,你可以这样做:

if resp1 == "Yes" or resp1 == "yes" then

但是,对于您要实现的目标,这是一个更简单的解决方案:

if resp1:lower() == 'yes' then

事实上,你也可以清理你的循环。使其更具可读性。使用多行字符串代替多个print调用和break

repeat
    resp1 = io.read():lower() -- read in lowercased input

    if resp1 == 'yes' then
        print[[Well alright then, come on in.
Let me just take your blood sample like all the rest and you'll be good to go.]]
        break -- exit from the loop here
    elseif resp1 == 'no' then
        print[[Oh, your not? Then why are you up here?
Oh nevermind then. None of my business anyways. All I'm supposed to do is take a blood sample for everyone who enters the town.
So let us get that over with now, shall we?]]
        break
    else
        print'Please respond with Yes or No'
    end

until false -- repeat forever until broken

答案 1 :(得分:0)

我这样做了......

repeat
 print("Please respond with Yes or No.")
    resp1 = io.read()

    if resp1 == "Yes" or resp1 == "yes" then
        print("Well alright then, come on in.")
        print("Let me just take your blood sample like all the rest and you'll be good to go.")

    elseif resp1 == "No" or resp1 == "no" then
        print("Oh, your not? Then why are you up here?")
        print("Oh nevermind then. None of my business anyways. All I'm supposed to do is take a blood sample for everyone who enters the town.")
        print("So let us get that over with now, shall we?")
        else
        print("Please, use just yes or no!!")
     end

   until resp1 == "Yes" or resp1 == "No" and resp1 == "no" or resp1 == "yes"