Modifying Lists


Lists can be modified in various after they are created. Starting from our original list:

local x = { "a", "b", "c" }

We can modify values in the list by assigning values to an index:

-- update a value in the table

x[2] = "x"

print(x[1]) -- a
print(x[2]) -- x
print(x[3]) -- c

We can insert values using the table.insert function:

-- add a value to the end of the table

table.insert(x, "d")

print(x[1]) -- a
print(x[2]) -- x
print(x[3]) -- c
print(x[4]) -- d
-- add a value to the end of the table

table.insert(x, 2, "y")

print(x[1]) -- a
print(x[2]) -- y
print(x[3]) -- x
print(x[4]) -- c
print(x[5]) -- d

Likewise, we can also remove items using the table.remove function:

-- remove a value from the table

table.remove(x, 2)

print(x[1]) -- a
print(x[2]) -- d
print(x[3]) -- nil