Programming Fundamentals/Arrays/Lua

arrays.lua

edit
-- This program uses arrays to display temperature conversion tables 
-- and temperature as an array subscript to find a given conversion.
--
-- References:
--     https://www.mathsisfun.com/temperature-conversion.html
--     https://www.lua.org/manual/5.1/manual.html

function build_c(size)
    local c = {}
    local index
    local value
    
    for index = 1, size do
    	value = index * 9 / 5 + 32
        c[index] = value
    end
    
    return c
end

function build_f(size)
    local f = {}
    local index
    local value
    
    for index = 1, size do
    	value = (index - 32) * 5 / 9
        f[index] = value
    end
    
    return f
end

function display_array(name, array)
    local index
    
    for index = 1, #array do
        io.write(name, "[", index, "] = ", array[index], "\n")
    end
end

function find_temperature(c, f)
    local temp
    local size
    
    size = minimum(#c, #f)
    repeat
        io.write("Enter a temperature between 1 and ", size, "\n")
        temp = tonumber(io.read())
    until not (temp < 1 or temp > size)
    io.write(temp, "° Celsius is ", c[temp], "° Fahrenheit", "\n")
    io.write(temp, "° Fahrenheit is ", f[temp], "° Celsius", "\n")
end

function minimum(value1, value2)
    local result
    
    if value1 < value2 then
        result = value1
    else
        result = value2
    end
        
    return result
end

function main()
  local c
  local f
  
  c = build_c(100)
  f = build_f(212)
  display_array("C", c)
  display_array("F", f)
  find_temperature(c, f)
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