Tables keep related values together and let code read values by index.

table index Lua table indexes usually start at one, so `scores[1]` reads the first value.

Tables

bonus
tables.lua
Replay: real traced execution (multi-file project)
local scores = {82, 91, 76}
local bonus = 5
local firstScore = scores[1]
local adjustedScore = scores[2] + bonus

print("first=" .. firstScore)
print("adjusted=" .. adjustedScore)
local scores = {82, 91, 76}
local bonus = 0
local firstScore = scores[1]
local adjustedScore = scores[2] + bonus

print("first=" .. firstScore)
print("adjusted=" .. adjustedScore)
local scores = {82, 91, 76}
local bonus = 10
local firstScore = scores[1]
local adjustedScore = scores[2] + bonus

print("first=" .. firstScore)
print("adjusted=" .. adjustedScore)
  1. scores ← table: ⟨addr A⟩, bonus ← 5, firstScore ← 82, adjustedScore ← 96

    1local scores→ table: ⟨addr A⟩ = {82, 91, 76}2local bonus→ 5 = 5 --@bonus=0, 103local firstScore→ 82 = scores[1]824local adjustedScore→ 96 = scores[2]91 + bonus556print("first=" .. firstScore82)7print("adjusted=" .. adjustedScore96)
    outputfirst=82
    adjusted=96
  1. scores ← table: ⟨addr A⟩, bonus ← 0, firstScore ← 82, adjustedScore ← 91

    1local scores→ table: ⟨addr A⟩ = {82, 91, 76}2local bonus→ 0 = 03local firstScore→ 82 = scores[1]824local adjustedScore→ 91 = scores[2]91 + bonus056print("first=" .. firstScore82)7print("adjusted=" .. adjustedScore91)
    outputfirst=82
    adjusted=91
  1. scores ← table: ⟨addr A⟩, bonus ← 10, firstScore ← 82, adjustedScore ← 101

    1local scores→ table: ⟨addr A⟩ = {82, 91, 76}2local bonus→ 10 = 103local firstScore→ 82 = scores[1]824local adjustedScore→ 101 = scores[2]91 + bonus1056print("first=" .. firstScore82)7print("adjusted=" .. adjustedScore101)
    outputfirst=82
    adjusted=101

What Happens

  1. scores starts as 82, 91, and 76.
  2. bonus starts at 5.
  3. scores[1] reads 82.
  4. scores[2] + bonus adds 91 + 5.
  5. The program prints first=82 and adjusted=96.

Table Picture

| bonus | first value | adjusted value | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |

Try It

Exercise: tables.lua

Reproduce first=82 and adjusted=96, then use the pinned bonuses 0 and 10 to predict each adjusted value.