Vital.sandbox
Table

table.remove

Shared

Removes and returns an element from a table


Syntax

local value = table.remove(input, position = table.len(input))

Parameters

TypeNameDescription
tableinputTable to be removed from
intpositionIndex of element to remove

Returns

TypeNameDescription
anyvalueRemoved element on successful execution, or nil if index is empty

Examples

Remove the last element
local t = {1, 2, 3, 4}
local removed = table.remove(t)

engine.print("info", removed) --4
engine.print("info", table.concat(t, ", ")) --1, 2, 3
Remove an element at a specific position
local t = {"a", "b", "c", "d"}
local removed = table.remove(t, 2)

engine.print("info", removed) --b
engine.print("info", table.concat(t, ", ")) --'a, c, d'
Remove the first element
local t = {10, 20, 30}
local removed = table.remove(t, 1)

engine.print("info", removed) --10
engine.print("info", table.concat(t, ", ")) --'20, 30'
Pop the top element off a stack
local stack = {"first", "second", "third"}
local top = table.remove(stack)

engine.print("info", top) --'third'
engine.print("info", #stack) --2
Dequeue the first element from a queue
local queue = {"task1", "task2", "task3"}
local next = table.remove(queue, 1)

engine.print("info", next) --'task1'
engine.print("info", table.concat(queue, ", ")) --'task2, task3'
Remove all elements one by one
--Remove all elements
local t = {1, 2, 3}

while table.len(t) > 0 do
    local value = table.remove(t)
    engine.print("info", value)
end

--[[
Output: 
3
2
1
]]
Return nil when removing from an empty table
local t = {}
local removed = table.remove(t)

engine.print("info", removed) --nil
Remove a middle element
local colors = {"red", "green", "blue", "yellow"}
table.remove(colors, 3)

engine.print("info", table.concat(colors, ", ")) --'red, green, yellow'
Process and remove elements in order
local tasks = {"a", "b", "c"}

while #tasks > 0 do
    local task = table.remove(tasks, 1)
    engine.print("info", "Processing:", task)
end

On this page