Lua unpack() 乱七八糟的参数 [英] Lua unpack() messing arguments

查看:32
本文介绍了Lua unpack() 乱七八糟的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个测试函数,它只是打印传递给它的值

I have this test function which simply prints values passed to it

function test1(...)
  for k, v in ipairs(arg) do
    print(v)    
  end
end

function test2(...)
  for k, v in pairs(arg) do
    print(v)    
  end
end

-- GOOD behavior
test1(1, 2, 3, 4) -- produces 1 2 3 4
test2(1, 2, 3, 4) -- produces 1 2 3 4

-- BAD behavior
test1( unpack({1,2}), 3, 4) -- produces 1 3 4
test2( unpack({1,2}), 3, 4) -- produces 1 3 4 3

有人可以向我解释这种行为吗?

Can someone explain this behavior to me ?

推荐答案

此行为并非特定于 unpack.Lua 参考手册说:

This behavior is not specific to unpack. The Lua Reference Manual says:

"函数调用和 vararg 表达式都可能产生多个值.如果将函数调用用作语句(参见第 3.3.6 节),则其返回列表将调整为零元素,从而丢弃所有返回值.如果一个表达式用作表达式列表的最后(或唯一)元素,然后不做任何调整(除非表达式被括在括号中).在所有其他上下文中,Lua 将结果列表调整为一个元素, 要么丢弃除第一个值以外的所有值,要么在没有值时添加一个 nil."

"Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see §3.3.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 expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values."

(我的重点)

这篇关于Lua unpack() 乱七八糟的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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