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

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为可变参的第一个元素。第三个参数是个可变参他取可变参的剩余参数


posted @ 2018-04-26 20:39  瓜蛋  阅读(5847)  评论(0编辑  收藏  举报