本文翻譯自 LUA官方文檔express
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).app
當一個函數被調用,除非是一個可變參數函數,不然函數調用時的參數長度與函數的參數一一對應。可變參數用三個點表示 ... ,在參數列表最後。一個可變參數不會有一個對應參數列表。他會收集全部的參數放進一個變參表式裏(三個點)。這個表達式的值表示全部參數值。它與函數返回多返回值的那種狀況是類似的。若是一個變參表達式在其它表達式內部或者在一些表達式的中間,他只返回是一個元素例如:local cc,dd,ee = a,...,34 。若是這個表達式是在表達式列表的最後一個,他不會對參數進行調和除非用一個括號。less
As an example, consider the following definitions:ide
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爲可變參的第一個元素。第三個參數是個可變參他取可變參的剩餘參數