util.table.remove

Shared

Removes and returns an element from a table


Syntax

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

Parameters

TypeNameDescription
tableinputTable to remove 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 = util.table.remove(t)

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

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

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

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

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

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

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

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

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

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

On this page