加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 21:42:12 所属栏目:大数据 来源:网络整理
导读:这是我看到的: function test(...) for i,v in ipairs({...}) do print(v) endend-- This is expected test(unpack({1,2}))12-- When I mix unpack and regular arguments-- What happened to 2? test(unpack({1,2}),3)13-- What happened to 3? test(unpac
这是我看到的:

> 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读