Category:vararg

From Garry's Mod
Jump to: navigation, search

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.

Examples

Example

Finds the average of a set of numbers.

function average(...)
	local args = {...} 
    local result = 0

	for k, v in pairs(args) do
		result = result + v
	end

	return result / #args
end

print(average(5, 15, 30, 7, 52))

Output:

21.8

This category currently contains no pages or media.

Personal tools
Navigation