Tables as lists
Lua has exactly one data structure: the table. Used with numbered positions, it is a list:
local fruits = {"mango", "banana", "guava"}
print(fruits[1]) -- mango (Lua counts from 1, not 0!)
print(#fruits) -- 3 # gives the length
fruits[#fruits + 1] = "orange" -- add to the end
Looping with ipairs
ipairs gives each position and value, in order:
for i, fruit in ipairs(fruits) do
print(i, fruit)
end
Use _ for a value you do not need: for _, fruit in ipairs(fruits) do.
The table library
table.insert(fruits, "pear") -- add to the end
table.insert(fruits, 1, "apple") -- add at position 1
table.remove(fruits, 2) -- remove position 2
table.sort(fruits) -- sort in place, A to Z
print(table.concat(fruits, ", ")) -- join into one string
table.sort changes the table itself. To keep the original, copy it first. table.sort(list, function(a, b) return a > b end) sorts biggest first.
Your task
average(list): the mean of the numbers.sorted_copy(list): a new, sorted table; the original stays unchanged.join_names(names):"Ana","Ana and Tino","Ana, Tino and Rudo".