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

use*_*382 2 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"
Run Code Online (Sandbox Code Playgroud)

Rya*_*ein 5

您的问题是与此行:

if resp1 == "Yes" or "yes" then
Run Code Online (Sandbox Code Playgroud)

这是两个单独的表达式,在Lua中,除nil和以外的所有内容false都是真实值,因此它将选择该if语句来运行,因为true就条件而言,Lua中的字符串(甚至是空字符串)都会求值。如果可以帮助您理解,可以这样考虑:

if (resp1 == "Yes") or ("yes") then
Run Code Online (Sandbox Code Playgroud)

如果您确实想resp1与两个值进行比较,则可以这样做:

if resp1 == "Yes" or resp1 == "yes" then
Run Code Online (Sandbox Code Playgroud)

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

if resp1:lower() == 'yes' then
Run Code Online (Sandbox Code Playgroud)

实际上,您也可以清理循环。使它更具可读性。也使用多行字符串而不是多个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
Run Code Online (Sandbox Code Playgroud)