Vital.sandbox
Table

table.unpack

Shared

Unpacks table elements into individual values


Syntax

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

Parameters

TypeNameDescription
tableinputTable to be unpacked
intstart_atPosition where unpacking starts
intend_atPosition where unpacking ends

Returns

TypeNameDescription
......Unpacked values from the table

Examples

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

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

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

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

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

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

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

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

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

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 = table.unpack(t)

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 = table.unpack(week, 1, 3)

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

On this page