本文翻譯自 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為可變參的第一個元素。第三個參數是個可變參他取可變參的剩余參數
