# Thread: [Lua] Temperature Converter

1. ## [Lua] Temperature Converter

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: ")

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

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: ")

if tonumber(temp) then
temp = tonumber(temp)

if temp == 1 or temp == 2 then
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.")

-- I operate in windows, if you use a version of Unix then replace cls with 'clear'
os.execute("cls")

end```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured

Click Here to Expand Forum to Full Width

×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.