2

我对 lua 和一般编程非常陌生,目前正在制作一个基本程序来熟悉 if/else/elseif 和 i/o。

基本上,它会询问您是男孩还是女孩,然后相应地打印您的身份。

虽然,我每次运行程序时都会遇到一个问题,它总是会打印出你是个男孩。

对不起,如果我是一个白痴,任何帮助表示赞赏!

代码如下;

io.write("Hello, are you a boy or a girl?\n")
answer = io.read()
if answer == "boy" or "Boy" then
io.write("Oh, so you're a boy, huh?")
elseif answer == "girl" or "Girl" then
io.write("Oh, so you're a girl, huh?")
else
io.write("Wow, i've never heard of an "..answer.." before!\n")
end
4

2 回答 2

2

尝试

io.write("Hello, are you a boy or a girl?\n")

answer = io.read()

if answer == "boy" or answer == "Boy" then
  io.write("Oh, so you're a boy, huh?")
elseif answer == "girl" or answer == "Girl" then
  io.write("Oh, so you're a girl, huh?")
else
  io.write("Wow, i've never heard of an "..answer.." before!\n")
end

解释

文档说:

如果此值不同于 nil 和 false,则析取运算符或返回其第一个参数;否则,或返回其第二个参数。

如果 answer == "girl" 的步骤:

  1. answer == "boy" or "Boy"
  2. false or "Boy"
  3. "Boy"
  4. 字符串被视为 true -> 执行 if
于 2013-10-04T12:21:17.983 回答
2

尝试替换这个:

if answer == "boy" or "Boy" then

有了这个:

if answer == "boy" or answer == "Boy" then

其他情况类似。

于 2013-10-04T12:25:36.670 回答