Skip to content
Tables as Arrays
step 1/5

Reading — step 1 of 5

Learn

~1 min readTables — The One Data Structure

The table is Lua's only built-in container. It's an associative array — a hash map where keys can be any value (except nil). When keys are sequential integers starting at 1, it acts as an array.

Crucial: Lua arrays are 1-indexed, not 0-indexed.

local fruits = { "apple", "banana", "cherry" }
print(fruits[1])   -- apple
print(#fruits)     -- 3  (length)

table.insert(fruits, "date")           -- append
table.insert(fruits, 1, "avocado")     -- insert at position 1
table.remove(fruits, 1)                -- remove at position 1

-- iterate
for i, v in ipairs(fruits) do
    print(i, v)
end

ipairs walks integer keys 1..n in order. #t returns the length, but only for sequence-like tables (no holes).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…