table.unpack()仅返回第一个元素 [英] table.unpack() only returns the first element

查看:435
本文介绍了table.unpack()仅返回第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could somebody explain to me why table.unpack() returns the first table element only when it is used in a function call with additional parameters after 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感兴趣.

I don't understand why the second line just prints 1 Test. I'd expect it to print 1 2 3 4 5 Test. Can somebody explain this behaviour? I'd also be interested in how I can make the second call to print 1 2 3 4 5 Test.

推荐答案

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

table.unpack returns multiple values. The defined behavior in that case is that if it is not the last one in a list of expressions then all but the first returned value will be discarded.

摘录自:

Lua始终根据调用的情况调整函数的结果数量.当我们将函数作为语句调用时,Lua会丢弃所有结果.当我们使用调用作为表达式时,Lua仅保留第一个结果.仅当调用是表达式列表中的最后一个(或唯一)表达式时,我们才能获得所有结果.

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.

作为一种解决方法,您可以将其余参数附加到表中,并以这种方式使表成为最后一个参数.

As a workaround you can append the rest of the arguments to the table and make the table the last argument that way.

这篇关于table.unpack()仅返回第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆