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
4 years ago
Edited 4 years ago

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

01function func(supplement, data1, data2)
02    print(supplement, data1, data2)
03end
04 
05local data = {
06    "Isaiah",
07    "Daniel"
08}
09 
10func("Camilla", table.unpack(data))
11-- output: Camilla, Isaiah, Daniel

notice what happens if I reverse the arguments

1function func(data1, data2, supplement)
2    print(data1, data2, supplement)
3end
4 
5-- same data
6 
7func(table.unpack(data), "Camilla")
8-- 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 4 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

1function r2()
2  return "a", "b"
3end

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

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

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

1print(r2(), "c") --> a, c
2print("c", r2()) --> c, a, b
Ad

Answer this question