Tables: The Basics

Any value except nil and NaN can be a key. Floats with integer values are normalized (t[1.0] is the same key as t[1]).

t.name is syntactic sugar for t["name"].

-- Array-like (sequence): indices start at 1!
local colors = {"red", "green", "blue"}
print(colors[1], #colors)               --> red  3
colors[#colors + 1] = "yellow"          -- append
table.insert(colors, "purple")          -- append
table.insert(colors, 1, "black")        -- insert at position 1
table.remove(colors)                    -- remove the last element
table.remove(colors, 1)                 -- remove the first element

-- Dictionary-like (record)
local person = {name = "Ana", age = 30, ["favorite color"] = "blue"}
print(person.name, person["age"], person["favorite color"])
person.email = "[email protected]"        -- add a field
person.age = nil                        -- remove a field (assigning nil deletes it)

-- Mixed and nested
local config = {
    "positional 1",
    "positional 2",
    debug = true,
    server = {host = "localhost", port = 8080},
    [10] = "explicit index",
    [true] = "boolean key",
}
print(config[1], config.server.port, config[10])

-- Tables are references
local t1 = {1, 2, 3}
local t2 = t1               -- same table
t2[1] = 99
print(t1[1])                --> 99
print({} == {})             --> false (different tables)

-- Iteration
for i, v
…