root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 20 min

Tables

โš‘ Report an issue with this lesson
local courses = {"HTML", "SQL", "Python"}  -- array-style table
print(courses[1])  -- "HTML" -- Lua indexes from 1, not 0

local prices = {
  html = 29.99,
  sql = 59.99,
}
print(prices.html)  -- 29.99

for key, value in pairs(prices) do
  print(key, value)
end

Tables are Lua's only real data structure -- one type doing the job of arrays, dictionaries, and (as you'll see next) objects.

An important quirk to internalize early: the array-style table {"HTML", "SQL", "Python"} and the key-value table {html = 29.99} are really the exact same underlying data structure -- a general-purpose table just happens to use consecutive integer keys starting at 1 in the first case. This means you can freely mix both styles in a single table:

local course = {
  "HTML",          -- this becomes course[1]
  title = "HTML Fundamentals",
  price = 29.99,
}
print(course[1])      -- "HTML"
print(course.title)   -- "HTML Fundamentals"

Because pairs() walks every key in a table (both the integer "array part" and any named keys) in an unspecified order, never rely on pairs() producing keys in the order you wrote them. When order actually matters -- like printing a list of courses in a specific sequence -- use ipairs() instead, which only walks the integer-indexed part of the table, in order, stopping at the first nil:

local courses = {"HTML", "SQL", "Python"}

for i, name in ipairs(courses) do
  print(i, name) -- always prints 1 HTML, 2 SQL, 3 Python, in that order
end

Checking table length and removing/inserting elements uses a small family of built-in functions:

print(#courses)              -- 3, the "length operator" (only reliable on array-style tables)
table.insert(courses, "Lua Mastery")   -- appends to the end
table.insert(courses, 1, "Intro")      -- inserts at position 1, shifting the rest
table.remove(courses, 2)               -- removes and returns the element at index 2
table.sort(courses)                     -- sorts the array part in place

Because a Lua table is a reference type (like a list or dict in Python), assigning it to another variable or passing it to a function shares the same underlying table rather than copying it -- mutating it through one reference is visible through every other reference to it.

Try it yourself

Exercise: Add a third price to the prices table, then loop with pairs() and print each.
Expected output: open-ended โ€” there's no single correct output here, just get your code running without errors.
lua
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

9 more lessons โ€” including Capstone project: a course catalog script โ€” plus a certificate are waiting.

Unlock the full course โ€” $149.99