Difference between revisions of "Lua: Vararg"

From Mario Fan Games Galaxy Wiki
m
m (i dunno what i was smoking when i first wrote this)
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 parameters, 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 table passed to the function, containing the arguments that were provided. A function can only contain one vararg statement, which should be the last parameter.
+
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 parameters, 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 should be the last parameter.
  
 
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">function choose(...)
+
  <source lang="lua" enclose="div">function choose(...)
     local args = {...} -- brackets are optional for vararg, because it's already a table
+
     local args = {...}
 
     return args[math.random(#args)]
 
     return args[math.random(#args)]
 
end</source>
 
end</source>
  
 
Vararg statements can even be used along with explicit parameters, like: ''function test(abc, xyz, ...)''.
 
Vararg statements can even be used along with explicit parameters, like: ''function test(abc, xyz, ...)''.

Revision as of 21:55, 16 July 2009

Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

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 parameters, 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 should be the last parameter.

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 can even be used along with explicit parameters, like: function test(abc, xyz, ...).