Syntax
local topics = {"Tables", "Loops"}
local profile = {name = "Ada"}
print(topics[1])
print(profile.name)Examples
Remove an item while keeping a sequence intact
table.remove shifts the later entries down. That keeps ipairs able to visit every remaining item in order.
local topics = {"Tables", "Loops", "Functions"}
local removed = table.remove(topics, 2)
print("Removed: " .. removed)
for index, title in ipairs(topics) do
print(index .. ": " .. title)
end
print("Length: " .. #topics)
- Output is Removed: Loops, then 1: Tables, 2: Functions, and Length: 2. table.remove also returns the removed value.
- Setting topics[2] = nil would remove the key without moving Functions down. ipairs stops at the first absent integer key, so that hole would stop the traversal early.
- For this dense sequence, # gives its length. Do not use # as a count of dictionary entries or rely on its result for a table with holes.
See why changing an alias changes the original
Named fields are useful for a record. A second variable can point to the same record, so a change through either name is visible through both.
local profile = {name = "Ada", completed = 2}
local alias = profile
alias.completed = alias.completed + 1
print(profile.name .. ": " .. profile.completed)
print(profile == alias)
local fieldCount = 0
for _ in pairs(profile) do
fieldCount = fieldCount + 1
end
print("Fields: " .. fieldCount)
- Output is Ada: 3, then true, then Fields: 2. The assignment did not create a second table; both variables refer to the same one.
- profile.name is shorthand for profile["name"]. pairs visits the present fields, without promising their order; the loop counts them regardless of that order.
- Add profile.active = false and the field count becomes 3. Assign nil instead and the key is absent: false is a stored value, while nil removes a field.
Best practices
- Keep sequences dense when using ipairs, # or table.remove.
- Count dictionary entries with pairs rather than #, and never depend on pairs ordering.
- Copy fields into a new table if you need independent top-level state; nested tables would still need their own copying policy.
Runtime & versions
Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Lua reference manuals