Here is a simple temperature converter code written in Lua. It first ask for the user to enter in some value for the degrees in which will be converted. Then it ask the user to chose to convert Fahrenheit to Celsius or vise-versa. Then depending on which operation the user chose, it will convert the degrees and print out the new value.
Code:--Our functions to convert Fahrenheit to Celsius and vise-versa function fahrenheit_to_celsius(fahrenheit) return (fahrenheit - 32) * 5 / 9 end function celsius_to_fahrenheit(celsius) return celsius * 9 / 5 + 32 end --Inifinite loop while true do --The value to convert val = nil repeat io.write("Enter in a degrees value: ") temp = io.read() if tonumber(temp) then val = tonumber(temp) else io.write("That was an invalid number.\n") end until val ~= nil --Loop until the user enters in a valid number menu = nil repeat io.write("\nConvert Fahrenheit to Celsius: 1\n") io.write("Convert Celsius to Fahrenheit: 2\n") io.write("Chose option 1 or option 2: ") temp = io.read() if tonumber(temp) then temp = tonumber(temp) if temp == 1 or temp == 2 then menu = tonumber(temp) else io.write(temp .. " is an invalid option.\n") end else io.write(temp .. " is an invalid number.\n\n") end until menu ~= nil --Loop until the user enters in a valid menu option --The converted degrees newVal = nil --Do the conversion if menu == 1 then newVal = fahrenheit_to_celsius(val) io.write("\n" .. val .. " degrees Fahrenheit is " .. newVal .. " degrees Celsius\n") else newVal = celsius_to_fahrenheit(val) io.write("\n" .. val .. " degrees Celsius is " .. newVal .. " degrees Fahrenheit\n") end io.write("Press the enter key to restart.") io.read() -- I operate in windows, if you use a version of Unix then replace cls with 'clear' os.execute("cls") end


Reply With Quote