gpt4 book ai didi

lua - 在 Lua 中使用 if、elseif 和 else 重复 Until Loop

转载 作者:行者123 更新时间:2023-12-02 04:43:32 25 4
gpt4 key购买 nike

我是 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"

最佳答案

您的问题与此行有关:

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

关于lua - 在 Lua 中使用 if、elseif 和 else 重复 Until Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com