LUA可变长参数 ... 三个点
本文翻译自 LUA官方文档
When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a vararg function, which is indicated by three dots ('...
') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a vararg expression, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses).
当一个函数被调用,除非是一个可变参数函数,否则函数调用时的参数长度与函数的参数一一对应。可变参数用三个点表示 ... ,在参数列表最后。一个可变参数不会有一个对应参数列表。他会收集所有的参数放进一个变参表式里(三个点)。这个表达式的值表示所有参数值。它与函数返回多返回值的那种情况是相似的。如果一个变参表达式在其它表达式内部或者在一些表达式的中间,他只返回是一个元素例如:local cc,dd,ee = a,...,34 。如果这个表达式是在表达式列表的最后一个,他不会对参数进行调和除非用一个括号。
As an example, consider the following definitions:
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
Then, we have the following mapping from arguments to parameters and to the vararg expression:
CALL PARAMETERS
f(3) a=3, b=nil --没有为b传参数则b为nil
f(3, 4) a=3, b=4 --参数一一对应
f(3, 4, 5) a=3, b=4 --多余传参数无作用
f(r(), 10) a=1, b=10 --可变参数在中间,表达值的值则是第一个变参列表元素
f(r()) a=1, b=2 --可变参数在最后面,不受影响
g(3) a=3, b=nil, ... --> (nothing) --b参数和...参数都没有传参数则为nil
g(3, 4) a=3, b=4, ... --> (nothing) --没有为可变参数传参则为nil
g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 --可变参数为最后一个,则自动收集参数列表到可变参数
g(5, r()) a=5, b=1, ... --> 2 3 --第二个参数b可传的是一个可变参,则b为可变参的第一个元素。第三个参数是个可变参他取可变参的剩余参数