Log in to vote

table.unpack with subsequent arguments?

Asked by 4 days ago
Edited 4 days ago

hello, I was using the table.unpack method and I noticed some strange behavior.

function func(supplement, data1, data2)
    print(supplement, data1, data2)

local data = {

func("Camilla", table.unpack(data))
-- output: Camilla, Isaiah, Daniel

notice what happens if I reverse the arguments

function func(data1, data2, supplement)
    print(data1, data2, supplement)

-- same data

func(table.unpack(data), "Camilla")
-- output: Isaiah, Camilla, nil

now this isn't a huge problem because I could even just unpack these into variables first then pass them in. I am wondering if anybody knows why this happens?

1 answer

Log in to vote
Answered by
eLunate 5136 Trusted Moderation Voter Community Moderator
4 days ago

That's really simple, and it's just basic Lua variadic behaviour. For any function which has multiple returns, it will be reduced to its first term if it is added anywhere but the tail of a tuple.

Consider this

function r2()
  return "a", "b"

This returns two values, as you'd expect. And, as you'd expect,

print(r2()) --> a, b

This prints two values. But only if the function is the last in the list.

print(r2(), "c") --> a, c
print("c", r2()) --> c, a, b

Answer this question