Results 1 to 1 of 1

Thread: [Lua] Temperature Converter

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,698

    [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: ")
    		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
    Last edited by dday9; Jun 12th, 2014 at 05:18 PM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

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



Click Here to Expand Forum to Full Width