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

table.unpack with subsequent arguments?

Asked by
Speedmask 661 Moderation Voter
3 years ago
Edited 3 years ago

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

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

local data = {
    "Isaiah",
    "Daniel"
}

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)
end

-- 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
1
Answered by 3 years 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"
end

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
Ad

Answer this question