Lua code elseif not working

140 views Asked by At

This is all about accepting input from user and searching with that particular text.

Playing with string.gsub.

io.write("ENTER ANY STORY :-D ")
story=io.read()
io.write("\t OKAY!, THAT'S NICE :-D  ")
io.write("\t DO YOU WANT TO REPLACE ANY TEXT:?  ")
accept=io.read()
if accept=="YES" or "yes" then
  io.write("\t WHICH TEXT TO REPLAE?  ")
  replace=io.read()
  --HERE IS THE REPLACING TEXT
  io.write("\t WITH WHAT:?   ")
  with=io.read()
  result=string.gsub(story,replace,with)
  print("\t THE REPLACED TEXT IS: ",result)
elseif accept=="NO" or "no" then
  print(result)
end

Bug: The elseif loop isn't working!!

2

There are 2 answers

4
luther On

== and or work like mathematical operators in that they are evaluated one at a time, with the == being evaluated first. If accept is 'no', accept=="YES" or "yes" will be evaluated like this:

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

In Lua, all values except nil and false are truthy, so your if block will always run instead of your elseif block.

As said in the comments, accept:upper()=="YES" will fix it. accept:upper() returns a string where all the letters of accept are converted to upper case, so then you only have to compare it to one value.

0
Naga Lokesh Kannumoori On

Try this..

io.write("ENTER ANY STORY :-D ")
story=io.read()
io.write("\t OKAY!, THAT'S NICE :-D  ")
io.write("\t DO YOU WANT TO REPLACE ANY TEXT:?  ")
accept=io.read()
if accept=="YES" or accept == "yes" then
  io.write("\t WHICH TEXT TO REPLAE?  ")
  replace=io.read()
  --HERE IS THE REPLACING TEXT
  io.write("\t WITH WHAT:?   ")
  with=io.read()
  result=string.gsub(story,replace,with)
  print("\t THE REPLACED TEXT IS: ",result)
elseif accept=="NO" or accept == "no" then
  print(result)
end