Adding and removing elements

Arrays and collections / Arrays

local primes = {2, 5, 7}
-- primes = 2, 5, 7
print("primes = " .. table.concat(primes, ", "))

-- Without a position insert appends
table.insert(primes, 11)
-- primes = 2, 5, 7, 11
print("primes = " .. table.concat(primes, ", "))

-- With a position the rest moves up
table.insert(primes, 2, 3)
-- primes = 2, 3, 5, 7, 11
print("primes = " .. table.concat(primes, ", "))

-- remove takes out by position and returns it
local removed = table.remove(primes, 1)
-- removed = 2
print("removed = " .. removed)
-- primes = 3, 5, 7, 11
print("primes = " .. table.concat(primes, ", "))

-- Without a position it takes the last one
local last = table.remove(primes)
-- last = 11
print("last = " .. last)

-- An empty table gives nil, not an error
local nothing = table.remove({})
-- nothing = nil
print("nothing = " .. tostring(nothing))

-- Valid positions are 1 to #primes + 1
local ok, err = pcall(table.insert, primes, 9, 13)
-- ok = false
-- err = bad argument #2 to 'table.insert'
-- (position out of bounds)
print("ok = " .. tostring(ok))
print("err = " .. err)