Unpack() returns only one value when returning it together with other values using commas

For me this only returns the first X part of the Vector3 and then the “hi”, but when you don’t have those commas returning multiple values it returns all the parts of the Vector3. This is pretty strange behavior and i’d like to fix it.

This is just the test of it:

local function PutTogether(d)
    
    return unpack(Vector3ToTable((d:GetPivot() * CFrame.new(-5,0,0)).p)),"hi"
end

Can you post the Vector 3ToTable function?

That is strange. My guess is that because the unpack function stores multiple variables in a tuple, Roblox gets confused when you try to return something after the unpack function. To work around this bug, you could return any variables first and put the unpacked table as the last thing to be returned. It should work if you do:

local function PutTogether(d)
    return "hi", unpack(Vector3ToTable((d:GetPivot() * CFrame.new(-5,0,0)).p))
end

This is due to how multi values work. @Jack_999 this is not a bug, just a quirk of lua.

unpack returns all of the contents of a table from index 1 to #table, like an ipairs loop, so, it works as multiple values.

In lua, when multiple values are simplified into one, for example, like this: (1, 2, 3) the first value is selected. The reason unpack is cutting out the second and third values is basically because lua treats call(), something as two values, whereas it treats call() itself with no commas as multiple values (if it returns multiple values when the call finishes), and the reason it works on the end is kind of for the same reason, it treats each bit as a single value up until that last bit where you do the function call, and then it doesn’t have commas in front.

It’s sort of because lua “sees” the commas before the function is called.

You could just do something like this:

local function PutTogether(d)
    local vector = (d:GetPivot() * CFrame.new(-5,0,0)).Position
    return vector.X, vector.Y, vector.Z, "hi"
end

And, a minor criticism, but, you probably don’t want to be turning a vector into a table anyways, it probably isn’t ideal for performance or memory, or your programming, except maybe if you’re reusing the table so you can modify the components without creating new vectors. I’m not sure that that’s faster anymore with the new native Vector3 stuff either but I haven’t tested.

If you use that in your code a lot, I might suggest something like this:

local function unpackVector3(vector)
    return vector.X, vector.Y, vector.Z
end
1 Like

@Hexcede is right, for more info: Everything You Didn’t Want to Know About Lua’s Multi-Values - Benaiah Mischenko