Lua elseif doesn't work correctly

When I try to use it elseif

, it doesn't work. In the case of the code below, no matter what number the user enters, the only code that gets executed is the code in the if statement.

io.write("do you want to convert from celsius to farenheit (1), or the other way around (2)?")
pref = io.read()
if pref == 1 then
  io.write("Hi there! what your temperature in celsius? ")
  local cel = io.read()
  far = (cel*1.8+32)
  io.write("That temperature in farenheit is: " .. far)
elseif pref == 2 then
  io.write("Hi there! what your temperature in farenheit? ")
  local far = io.read()
  cel = ((far-32)/1.8)
  print("That temperature in celsius is: " .. cel)
end

      

+3


source to share


1 answer


The problem is not with elseif

. The problem is what is io.read()

returning a string. Or convert it to a number:

pref = tonumber(io.read())

      



Or compare pref

with "1"

, "2"

.

+6


source







All Articles