Difference between revisions of "Lua: Vararg"
m (i dunno what i was smoking when i first wrote this) |
m |
||
Line 1: | Line 1: | ||
{{Lua}} | {{Lua}} | ||
− | A '''vararg''' statement is basically a group of arguments with a variable size. Usually, a function is defined to use only a certain number of | + | A '''vararg''' statement is basically a group of arguments with a variable size. Usually, a function is defined to use only a certain number of arguments, but a vararg statement allows it to take an arbitrary amount. In [[Lua]], a vararg statement is defined with three dots (...). This vararg statement represents a list of values (''not'' a table in itself!) passed to the function, containing the arguments that were provided. A function can only contain one vararg statement, which must be the last argument if there are other named arguments. |
The following function takes any number of values, chooses one at random, and returns it: | The following function takes any number of values, chooses one at random, and returns it: | ||
− | + | <source lang="lua" enclose="div">function choose(...) | |
local args = {...} | local args = {...} | ||
return args[math.random(#args)] | return args[math.random(#args)] | ||
end</source> | end</source> | ||
− | Vararg statements | + | Vararg statements are useful when passing information transparently from one function to another, for example table lookup functions: |
+ | |||
+ | <source lang="lua" enclose="div"> | ||
+ | function callEvent(event_name, ...) | ||
+ | events[event_name](...) | ||
+ | end | ||
+ | </source> |
Latest revision as of 22:03, 16 July 2009
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
A vararg statement is basically a group of arguments with a variable size. Usually, a function is defined to use only a certain number of arguments, but a vararg statement allows it to take an arbitrary amount. In Lua, a vararg statement is defined with three dots (...). This vararg statement represents a list of values (not a table in itself!) passed to the function, containing the arguments that were provided. A function can only contain one vararg statement, which must be the last argument if there are other named arguments.
The following function takes any number of values, chooses one at random, and returns it:
function choose(...)
local args = {...}
return args[math.random(#args)]
end
Vararg statements are useful when passing information transparently from one function to another, for example table lookup functions:
function callEvent(event_name, ...)
events[event_name](...)
end