table.unpack() 仅returns第一个元素

table.unpack() only returns the first element

有人可以向我解释为什么 table.unpack() returns 第一个 table 元素只有在 table.unpack() 之后带有附加参数的函数调用中才使用吗?

这是一些演示代码:

local a = {1,2,3,4,5}
print("Test", table.unpack(a))   -- prints "Test 1 2 3 4 5"
print(table.unpack(a), "Test")   -- prints "1 Test"

我不明白为什么第二行只打印 1 Test。我希望它打印 1 2 3 4 5 Test。有人可以解释这种行为吗?我也对如何进行第二次打印 1 2 3 4 5 Test.

感兴趣

table.unpack() 在任何一种情况下都返回相同的东西,但在第二种情况下 Lua 只需要一个值,所以它不会把它变成多个参数。当它是最后一个参数时 Lua 可以变成多个参数。

table.unpack returns 多个值。在这种情况下定义的行为是,如果它不是表达式列表中的最后一个,那么除了第一个返回值之外的所有返回值都将被丢弃。

来自book

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all of its results. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions.

作为解决方法,您可以将其余参数附加到 table 并使 table 成为最后一个参数。