Lua code elseif 语句无法运行

这个问题涉及接受用户输入并使用特定文本进行搜索。

string.gsub 进行了调试。

io.write("输入任何故事 :-D ")
story=io.read()
io.write("\t 没错! 非常好 :-D  ")
io.write("\t 你想要替换哪些文本吗:?  ")
accept=io.read()
if accept=="YES" or "yes" then
  io.write("\t 要替换哪些文本?  ")
  replace=io.read()
  --下面是替换文本的代码
  io.write("\t 要替换成什么?:   ")
  with=io.read()
  result=string.gsub(story,replace,with)
  print("\t 替换后的文本是: ",result)
elseif accept=="NO" or "no" then
  print(result)
end

错误: elseif 循环不起作用!

点赞
用户3574628
用户3574628

==or在逻辑上像数学运算符一样被逐个求值,其中==首先被求值。如果accept的值为'no'accept=="YES" or "yes"会像这样被求值:

(accept == "YES") or "yes"
('no' == "YES") or "yes"
false or "yes"
"yes"

在Lua中,除了nilfalse,所有值都是象征真的,因此您的if块将始终运行,而不是您的elseif块。

正如评论中所说,accept:upper()=="YES"将修复它。accept:upper()返回一个字符串,其中accept的所有字母都转换为大写,因此您只需要将其与一个值进行比较。

2018-05-06 16:16:09
用户7821343
用户7821343
io.write("请输入一个故事: ")
story=io.read()
io.write("\t好的!那很不错:D  ")
io.write("\t您想替换任何文本吗?  ")
accept=io.read()
if accept=="YES" or accept == "yes" then
  io.write("\t您想替换哪个文本?  ")
  replace=io.read()
  --这是替换文本的部分
  io.write("\t用什么替换?   ")
  with=io.read()
  result=string.gsub(story,replace,with)
  print("\t替换后的文本是:",result)
elseif accept=="NO" or accept == "no" then
  print(result)
end
2018-05-11 06:35:48