Unpack


unpack( table, [first], [last] )
table a numbered table of elements (list)
first (optional) the first number of the table to return
last (optional) the last number of the table to return

The unpack( table ) function is used to separate a table and return its values. The table passed as an argument must be a list, a table with numbered keys. Any non-numeric keys in the table will not be returned. 

Use multiple assignment to receive the multiple returns from this function:

a, b, c = 1, 2, 3
a, b, c = unpack( table )



For example, if we call unpack( table ), the function will return each value from within the list. In order to catch each value, we must provide multiple variables separated by commas.

table = {
	"apple",
	"banana",
	"cherry",
}

a,b,c = unpack( table )

print(a) --apple
print(b) --banana
print(c) --cherry


When passing the optional arguments, if we call unpack( table,i,j ), the function will return each value starting with table[i] and end with table[j] . In order to catch each value, we must provide multiple variables separated by commas.

table = {
	"apple",
	"banana",
	"cherry",
	"durian",
	"eggplant",
	"fig",
}

a,b,c,d,e,f = unpack( table,2,5 )

This may not return what you expect. Since we have named the entries in the table in alphabetical order, and the variables to receive the returned values are also alphabetical, it would make sense that a is always apple. However, remember that the first value returned is specified to be entry 2, which is banana.

So this is what is actually returned:

print(a) --banana
print(b) --cherry
print(c) --durian
print(d) --eggplant
print(e) --nil
print(f) --nil

Notice that the value of A is now "banana", because that was specified to be the first entry to be returned. Only 4 elements were returned in total because we also specified to stop after returning the 5th element of the table. And the variables E and F are nil because nothing returned after "eggplant" to be assigned to those variables.



Common Uses

The most common usage of the function unpack() is to save tokens when declaring variables. It is most commonly used with the  split() function to assign multiple variables from a single string. To save the most tokens, we can use split a string into a table, and then immediately unpack that table into separate variables. So you might see both functions nested like this: unpack( split() )

Example:

--single assignments
sprite=1
x=10
y=20
w=1
h=1
speed=2
jump=6
atk=10
def=5
--27 tokens

--split and unpack
sprite,x,y,w,h,speed,jump,atk,def=
unpack(split("1,10,20,1,1,2,6,10,5"))
--16 tokens

302

23 Nov 2023

Font