API unpack

From Wowpedia
Jump to: navigation, search

Returns values stored in a table's array portion.

... = unpack(t [, first [, last]])

Arguments

table - A table to unpack values from.
first 
number?Optional. Could be nil. - Index of the first value to return (default: 1).
last 
number?Optional. Could be nil. - Index of the last value to return (default: #t).

Returns

t[first], t[first+1], ..., t[last] 
Mixed - Values contained at indices first through last in the table.

Details

  • Warning 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]

Examples

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

 
  1. ^ Roberto Ierusalimschy 2003-11-30. Programming in Lua: 19.1 Array Size.