当我将 unpack() 作为 lua 的函数参数调用时会发生什么? [英] What is happening when I call unpack() as lua's function arguments?

查看:38
本文介绍了当我将 unpack() 作为 lua 的函数参数调用时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我看到的:

> function test(...)
>>  for i, v in ipairs({...}) do
>>    print(v)
>>  end
>>end

-- This is expected
> test(unpack({1,2}))
1
2
-- When I mix unpack and regular arguments
-- What happened to 2?
> test(unpack({1,2}), 3)
1
3
-- What happened to 3?
> test(unpack({}), 3)

-- When I put regular args before unpack, everything is fine:
> test(1, unpack({2, 3}))
1
2
3

当我将解压缩的参数与常规参数混合使用时,结果很奇怪.你能解释一下幕后发生了什么吗?

When I mix unpacked arguments with regular args, the result are weird. Could you explain what is happening under the hood?

推荐答案

我将引用 Lua 参考:

I'll quote the Lua reference:

函数调用和可变参数表达式都可能导致多个值.如果将表达式用作语句(仅适用于函数调用(见第 2.4.6 节)),然后它的返回列表被调整为零元素,从而丢弃所有返回的值.如果一个表达式是用作表达式列表的最后(或唯一)元素,然后不进行任何调整(除非调用包含在括号中).在所有其他上下文,Lua 将结果列表调整为一个元素,丢弃除第一个以外的所有值.

Both function calls and vararg expressions can result in multiple values. If an expression is used as a statement (only possible for function calls (see §2.4.6)), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, discarding all values except the first one.

如您所见,您的解包调用减少为一个返回值,因为它既不是您传递给测试的表达式列表中的最后一个也不是唯一的表达式:

As you see your unpack call is reduced to one return value as it is neither the last nor the only expression in the list of expressions you pass to test:

test(unpack({1,2}), 3)

在另一种情况下,答案很简单:

In the other case the answer is quite simple:

test(unpack({}), 3)

传递给 test 的第一个值是 nil.因此 for i, v in ipairs({...}) do end 不会做任何事情,因为你的表的第一个值是 nil as unpack({}) 返回 nil

The first value passed to test is nil. Therefor for i, v in ipairs({...}) do end will do nothing as your table's first value is nil as unpack({}) returns nil

ipairs (t)

返回三个值(一个迭代器函数、表 t 和 0)所以那个建设

Returns three values (an iterator function, the table t, and 0) so that the construction

 for i,v in ipairs(t) do body end

将迭代键值对 (1,t[1]), (2,t[2]), ...,直到第一个 nil 值.

will iterate over the key–value pairs (1,t[1]), (2,t[2]), ..., up to the first nil value.

这篇关于当我将 unpack() 作为 lua 的函数参数调用时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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