Programming Fundamentals/Conditions/Lua

conditions.lua

edit
-- This program asks the user to select Fahrenheit or Celsius conversion
-- and input a given temperature. Then the program converts the given 
-- temperature and displays the result.
--
-- References:
--     https://www.mathsisfun.com/temperature-conversion.html
--     https://www.lua.org/manual/5.1/manual.html

function get_choice()
    io.write("Enter F to convert to Fahrenheit or C to convert to Celsius:", "\n")
    choice = io.read()
    return choice
end

function get_temperature(label)
    local temperature
    
    print("Enter " .. label .. " temperature:")
    temperature = tonumber(io.read())
        
    return temperature
end

function calculate_celsius(fahrenheit)
    local celsius
    
    celsius = (fahrenheit - 32) * 5 / 9
        
    return celsius
end

function calculate_fahrenheit(celsius)
    local fahrenheit
    
    fahrenheit = celsius * 9 / 5 + 32
        
    return fahrenheit
end

function display_result(temperature, from_label, result, to_label)
    print(temperature .. "° " .. from_label .. " is " .. result .. "° " .. to_label)
end

function main()
    local choice
    local temperature
    local result
    
    choice = get_choice()
    if choice == "C" or choice == "c" then
        temperature = get_temperature("Fahrenheit")
        result = calculate_celsius(temperature)
        display_result(temperature, "Fahrenheit", result, "Celsius")
    elseif choice == "F" or choice == "f" then
        temperature = get_temperature("Celsius")
        result = calculate_fahrenheit(temperature)
        display_result(temperature, "Celsius", result, "Fahrenheit")
    else
        io.write("You must enter C to convert to Celsius or F to convert to Fahrenheit!", "\n")
    end
end

main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Lua compiler / interpreter / IDE.

See Also

edit