Programming Fundamentals/Arrays/Lua: Difference between revisions
Appearance
Content deleted Content added
Creating |
(No difference)
|
Revision as of 01:47, 19 February 2017
arrays.lua
-- This program uses arrays to display temperature conversion tables
-- and temperature as an array subscript to find a given conversion.
function build_c(size)
local c = {}
local index
for index = 1, size do
c[index] = index * 9 / 5 + 32
end
return c
end
function build_f(size)
local f = {}
local index
for index = 1, size do
f[index] = (index - 32) * 5 / 9
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 = get_minimum_size(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 get_minimum_size(c, f)
local size
size = #c
if size > #f then
size = #f
end
return size
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
Copy and paste the code above into one of the following free online development environments or use your own Lua compiler / interpreter / IDE.