API unpack
Jump to navigation
Jump to search
Returns values stored in a table's array portion.
... = unpack(t [, first [, last]])
Arguments
- t
- table - A table to unpack values from.
- first
- number? - Index of the first value to return (default: 1).
- last
- number? - Index of the last value to return (default:
#t
).
Returns
t[first], t[first+1], ..., t[last]
- Mixed - Values contained at indices
first
throughlast
in the table.
Details
Warning: Unless
last
is explicitly given, unpack() relies on the#
(array length) operator which can have undefined behaviour for tables holding nil values before the end of the array.[1]
Example
Typical usage:
unpack({1, 5, "Hearthstone"}) -- 1, 5, "Hearthstone"
unpack({1,2,3,4,5}, 2) -- 2, 3, 4, 5
unpack({1,2,3,4,5}, 1, 2) -- 1, 2
Unpacking tables with nil values:
-- Wrong
unpack({1,nil,3}) -- Might return 1; or might return 1, nil 3
-- Correct
unpack({1,nil,3}, 1, 3) -- Always returns 1, nil, 3
-- Alternative
unpack({1,nil,3,n=3}) -- Always returns 1, nil, 3
References
- ^ Roberto Ierusalimschy 2003-11-30. Programming in Lua: 19.1 Array Size.