我正在尝试制作一个'简单'的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())
答案 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
所做的更改是:
input == "y" or "Y"
没有按你的想法行事。相反,它评估为(input == "y") or ("Y")
,您想要它input == "y" or input == "Y"
。false
时,您需要将循环设置为"y" or "Y" or "n" or "N"
,否则循环将继续。 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())