Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Strange results from unpack() ?

Asked by 5 years ago
test = {"hello","there"}

print(unpack(test))-- Print 1

print("" .. unpack(test))-- Print 2

x = unpack(test)

print(x)-- Print 3

Print 1 outputs "hello there" as expected. Print 2 and Print 3 only output "hello". Why does unpack() only return the first thing in the table if you try to do anything with the data it's giving you?

0
For further reading on this topic: https://www.lua.org/pil/5.1.html chess123mate 5873 — 5y

2 answers

Log in to vote
4
Answered by 5 years ago
Edited 5 years ago

This is because unpack returns multiple values. It doesn't concatenate them all together for a single use. If you wanted to do that, you could use table.concat (for an array, of course). This is a consistent feature in Lua.

  • local x = f() will set x to the first result of f()

Lua supports multiple variable assignments, meaning a, b = 1, 2 is a valid variable assignment that results in a = 1; b = 2. However, if a is given more than one value, it cannot be multiple values at the same time. So Lua picks the first one it was given. For example...

local t = {1, 2, 3}
local a = unpack(t)

a is given the values 1, 2, 3 which doesn't make any sense. Therefore, Lua decides that a will be given the first value in the tuple-like arrangement, which is 1.

However, multiple values can be assigned to multiple variables at the same time. For example, if we did this...

local t = {1, 2, 3}
local a, b, c = unpack(t)

...then we would see that it assigned a = 1, b = 2, and c = 3. This is because it could map all of the given values from unpack(t) to a unique pointer. This is very reminiscent to how you define functions in mathematics. The definition of a function (in math) is as follows:

A relationship between x and y such that, for every x, there is a unique y-value

The behavior between mapping x's to y's in math is the exact same as mapping variables to values in Lua.

0
dang it, ninja'd User#24403 69 — 5y
0
Have 4 upvotes SirDerpyHerp 262 — 5y
Ad
Log in to vote
0
Answered by 5 years ago

Remember that in multiple variable assignment, additional results are discarded.

x = unpack(test)

is the same as

x = "hello","there"

"there" is discarded and x is assigned to "hello". This is true for any function call, not only unpack. x was assigned the first return value of unpack, which is "hello". These are not strange results.


Don't forget to hit that "Accept Answer" below if this helps!

Answer this question