Arrays

Type initialization / Collections

-- Arrays are tables, items are counted from 1
local prime_numbers = {2, 3, 5, 7, 11, 13, 17, 19}
local first = prime_numbers[1]
-- first = 2
-- The length operator # counts them
local count = #prime_numbers
-- count = 8

local game_list = {"soccer", "hockey",
                   "basketball"}
local games = table.concat(game_list, ", ")
-- games = soccer, hockey, basketball
-- Mixed types are fine
local host_and_port = {"192.168.100.1", 3002}
local port = host_and_port[2]
-- port = 3002

-- A list of records
local employees = {
  {first_name = "Anton", last_name = "Pavlov"},
  {first_name = "Elena", last_name = "Kirienko"},
}
local last = employees[2].last_name
-- last = Kirienko

-- 2 x 3 grid: each row is a new table
local grid = {}
for row = 1, 2 do
  grid[row] = {0, 0, 0}
end
grid[1][1] = 1
local grid_cell = grid[2][1]
-- grid_cell = 0

-- Trap: one table used twice is the SAME row
local shared = {0, 0, 0}
local same_row = {shared, shared}
same_row[1][1] = 1
local same_cell = same_row[2][1]
-- same_cell = 1

print("first = " .. first)
print("count = " .. count)
print("games = " .. games)
print("port = " .. port)
print("last = " .. last)
print("grid_cell = " .. grid_cell)
print("same_cell = " .. same_cell)