Garry's Mod Wiki

Concepts - Variable Number of Arguments (var args)

Variable Number of Arguments (var args)

Varargs are variable number of arguments, meaning the amount of arguments is undefined. The most notable function to take varargs is print.

To create a function with varargs, you must set the last parameter of the function to ... (that's three periods). You may use a combination of normal arguments with varargs, but the varargs must appear as the last parameter. Inside of the function's body, you may access each argument by creating a table of the varargs with { ... }.

In the table, each key is the respective number of the argument, with the value being the value passed.

Varargs are stored at negative indices, so functions such as debug.getlocal may access the values where -1 is the first vararg passed, -2 is the second, etc.

You may create varargs yourself with unpack.


Finds the average of a set of numbers.

function average( ... ) local args = { ... } local result = 0 for _, v in ipairs( args ) do result = result + v end return result / #args end print( average( 5, 15, 30, 7, 52 ) )
Output: 21.8