Tables as Arrays
Create and manipulate 1-indexed arrays with table.insert and table.remove.
1-Indexed Arrays
Lua arrays are tables with consecutive integer keys starting at 1. This differs from most languages which start at 0. The convention is universal in Lua — all standard library functions assume 1-based indexing. Out-of-bound access returns nil, not an error.
local colors = {"red", "green", "blue"}
print(colors[1]) -- red
print(colors[2]) -- green
print(colors[3]) -- blue
print(colors[0]) -- nil (no index 0)
print(#colors) -- 3 (length operator)table.insert and table.remove
table.insert(t, val) appends to the end. table.insert(t, pos, val) inserts at a position, shifting elements right. table.remove(t, pos) removes the element at pos (default: last), shifting elements left, and returns the removed value.
local stack = {}
table.insert(stack, "first")
table.insert(stack, "second")
table.insert(stack, "third")
print(#stack) -- 3
table.insert(stack, 2, "inserted")
print(stack[2]) -- inserted
local removed = table.remove(stack, 1)
print(removed) -- first
print(stack[1]) -- inserted