Lesson 6 of 8 · 9 min

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

  1. average(list): the mean of the numbers.
  2. sorted_copy(list): a new, sorted table; the original stays unchanged.
  3. join_names(names): "Ana", "Ana and Tino", "Ana, Tino and Rudo".
main.lua
local function average(list)
end

local function sorted_copy(list)
end

local function join_names(names)
end

print(join_names({"Farai", "Chipo", "Kuda"}))

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…