当我将unpack()作为lua的函数参数调用时会发生什么?

前端之家收集整理的这篇文章主要介绍了当我将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

当我将unpacked参数与常规args混合时,结果很奇怪.你能解释一下在幕后发生的事情吗?

解决方法

我引用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.

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

test(unpack({1,3)

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

test(unpack({}),3)

传递给test的第一个值是nil.因此,i,v in ipairs({…})do end将无效,因为你的表的第一个值是nil,因为unpack({})返回nil

ipairs (t)

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

06002

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

猜你在找的Lua相关文章