util.table.unpack

Shared

Unpacks table elements into individual values


Syntax

local ... = util.table.unpack(
    input,
    start_at = 1,
    end_at = util.table.len(input)
)

Parameters

TypeNameDescription
tableinputTable to unpack
intstart_atPosition where unpacking starts
intend_atPosition where unpacking ends

Returns

TypeNameDescription
any...Unpacked values from the table

Examples

Unpack all elements into variables
local t = {10, 20, 30}
local a, b, c = util.table.unpack(t)

core.engine.print("info", a, b, c) -- 10  20  30
Unpack a table directly into function arguments
local coords = {100, 200, 50}

core.engine.print("info", util.table.unpack(coords)) -- Same as core.engine.print("info", 100, 200, 50)
Unpack a subset of a table
local t = {1, 2, 3, 4, 5}
local a, b = util.table.unpack(t, 2, 3)

core.engine.print("info", a, b) -- 2  3
Unpack from a specific start position
local t = {"a", "b", "c", "d"}
local x, y, z = util.table.unpack(t, 2)

core.engine.print("info", x, y, z) -- 'b'  'c'  'd'
Unpack a single element
local t = {42}
local value = util.table.unpack(t)

core.engine.print("info", value) -- 42
Unpack a table containing nil values
local t = {1, nil, 3}
local a, b, c = util.table.unpack(t)

core.engine.print("info", a, b, c) -- 1  nil  3
Swap two variables using pack and unpack
local a, b = 10, 20
a, b = util.table.unpack({b, a})

core.engine.print("info", a, b) -- 20  10
Unpack color components into separate arguments
local color = {255, 128, 0}
local r, g, b = util.table.unpack(color)

setColor(r, g, b)
Unpack into multiple named variables
local data = {true, "success", 100}
local status, message, code = util.table.unpack(data)

core.engine.print("info", status, message, code) -- true  "success"  100
Extra variables are nil when unpacking past the end
local t = {1, 2}
local a, b, c, d = util.table.unpack(t)

core.engine.print("info", a, b, c, d) -- 1  2  nil  nil
Unpack a specific range from a table
local week = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
local first, second, third = util.table.unpack(week, 1, 3)

core.engine.print("info", first, second, third) -- 'Mon'  'Tue'  'Wed'

On this page