Lua中 unpack()函数如何导致参数顺序错乱?
- 内容介绍
- 文章标签
- 相关推荐
本文共计307个文字,预计阅读时间需要2分钟。
我有这个测试功能,它只是打印并传递给它的值+function test1(arg) for k,v in ipairs(arg) do print(v) end end function test2(arg) for k,v in pairs(arg) do print(v) end end--+良好行为test1(1, 2, 3, 4)+--+产生1 2 3 4test2“
我有这个测试功能,它只是打印传递给它的值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
有人可以向我解释这种行为吗?
此行为不是特定于解压缩.Lua Reference Manual说:
“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.“
(我的重点)
本文共计307个文字,预计阅读时间需要2分钟。
我有这个测试功能,它只是打印并传递给它的值+function test1(arg) for k,v in ipairs(arg) do print(v) end end function test2(arg) for k,v in pairs(arg) do print(v) end end--+良好行为test1(1, 2, 3, 4)+--+产生1 2 3 4test2“
我有这个测试功能,它只是打印传递给它的值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
有人可以向我解释这种行为吗?
此行为不是特定于解压缩.Lua Reference Manual说:
“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.“
(我的重点)

