JL123
JL123

Reputation: 71

Lua elseif not working properly

When I attempt to use elseif, it doesn't work. In the case of the code below, no matter which number the user inputs, the only code that runs is the code under 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's 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's your temperature in farenheit? ")
  local far = io.read()
  cel = ((far-32)/1.8)
  print("That temperature in celsius is: " .. cel)
end

Upvotes: 3

Views: 371

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

The problem is not with the elseif. The problem is because io.read() returns a string. Either convert it to a number:

pref = tonumber(io.read())

Or, compare pref with "1", "2" instead.

Upvotes: 6

Related Questions