Garry's Mod Wiki

Garry's Mod Wiki

Variadic Functions

Functions that take a variable amount of arguments are called variadic.


Example

The print function logs any number of values you supply it to the console.

print( 'These' , 'are' , 'a' , 'lot' , 'of' , 'arguments' , 1 , 2 , 3 )


Declaration

Variadic arguments can be declared with the name
... at the ends of a function's list of arguments.

function ( first , second , ... )

Calling the function with ( 1 , 2 , 3 , 4 ) results in:

  • first = 1
  • second = 2
  • ... = 3 , 4


Usage

You can use supply ... as an argument to another function.

sum( 1 , 2 , ... , 5 ) -- Same as sum( 1 , 2 , 3 , 4 , 5 )


Unpacking

You can also create variadic arguments by unpacking a table.

unpack({ 3 , 4 }) -- Same as `3 , 4`


Packing

The opposite can be achieved by packing a table.

local arguments = table.Pack( ... ) -- Same as { 3 , 4 }
local arguments = { ... } -- Shorthand Syntax




Example: Summation

Adds up a variable numbers of values.

Code

function sum ( ... ) local total = 0 for _ , value in ipairs({ ... }) do total = total + value end return total end

Test

print(sum(1,2,3))
Output: 6




Example: Average

Finds the mean of a variable numbers of values
using the previous example's summation function.

Function

function average ( ... ) return sum( ... ) / #{ ... } end

Test

print(average(1,2,3))
Output: 2.0

This site is a community mirror of the official Garry's Mod wiki.. This site is not maintained by Facepunch Studios.

Page content is automatically updated four times a day. Edits and history are not available.

Last Parsed: Loading...