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

重复,直到在Lua中使用if、elseif和else循环,lua,string-comparison,Lua,String Comparison,我是Lua的新手,这段代码有点问题。它应该使用io验证用户输入。读取然后运行正确的if、elseif或else语句。一旦用户输入正确的响应,代码应该结束。出于某种原因,代码将只运行初始的if语句。任何帮助都将不胜感激 repeat resp1 = io.read() if resp1 == "Yes" or "yes" then print("Well alright then, come on in.") print("Let me just

我是Lua的新手,这段代码有点问题。它应该使用
io验证用户输入。读取
然后运行正确的
if
elseif
else
语句。一旦用户输入正确的响应,代码应该结束。出于某种原因,代码将只运行初始的
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"

您的问题在于这一行:

if resp1 == "Yes" or "yes" then
这是两个独立的表达式,在Lua中,除了
nil
false
之外的所有内容都是真实值,因此它将在运行
语句时选择
,因为Lua中的字符串,即使是空字符串,就条件而言,其计算结果也是
true
。如果这有助于您理解,请这样想:

if (resp1 == "Yes") or ("yes") then
if resp1 == "Yes" or resp1 == "yes" then
如果您确实想将
resp1
与两个值进行比较,您可以这样做:

if (resp1 == "Yes") or ("yes") then
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
我是那样做的

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"