Lua Table Arrays
A table array is a table whose values sit in numbered slots in a row. Lua gives tools to add and remove values at the end or in the middle.
Insert grows the list
Each insert adds one value at the end. The length print after each step proves the growth.
local list = {"a", "b"}
print(#list)
table.insert(list, "c")
print(#list)
table.insert(list, "d")
print(#list)
print(list[4])Remove returns the value
table.remove with no position takes the last value. The removed value can be saved and printed.
local list = {10, 20, 30}
local gone = table.remove(list)
print(gone)
print(#list)
print(list[2])Insert in the middle shifts items
Inserting at position 3 moves the later items up one slot. A loop prints the full row in order.
local list = {"a", "b", "d"}
table.insert(list, 3, "c")
for i = 1, #list do
print(i .. ": " .. list[i])
endExample
local playlist = {"Sunrise", "River"}
table.insert(playlist, "Mountain")
table.insert(playlist, "Ocean")
local removed = table.remove(playlist, 2)
print("Removed: " .. removed)
for i = 1, #playlist do
print(i .. ": " .. playlist[i])
endKey points
- Array: A table array stores values in numbered slots in order.
- table.insert: table.insert(t, v) adds v at the end of the array.
- Insert position: table.insert(t, pos, v) puts v at pos and shifts later values up one slot.
- table.remove: table.remove(t) removes the last value and returns it.
- Length: The # operator gives the number of values in the array part of a table.
In this example, the playlist starts with two songs and table.insert adds Mountain and Ocean at the end. table.remove takes out the song at position 2, and its returned value is printed. The loop then prints the three songs left, numbered in order.
Note
Removing a value from the middle shifts later values down to fill the gap.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After local list = {1, 2, 3} and table.remove(list), what is #list?