Game Development Reference
In-Depth Information
The way to pass parameters to this type of function is as follows:
namedArrayParams({debug=true, 56,"One", color="red", false})
Note When calling a function in Lua with a table—for example,
someFunction({one=1,two=2}) —you can also call it as follows: someFunction {one=1, two=2} .
This can only be used if the table is the only parameter being passed to the function. It cannot be used
for any type of parameter other than a table value being passed.
Using Varargs
Varargs are similar to variable parameters, as described previously, but instead of a variable name,
they are defined by a special combination of three dots. Though they may seem a lot like table
arrays, they are different in the way that you can interact with them.
function passvarargs(...)
local a, b = ...
print(a, b)
end
a and b get the first and the second parameter passed; this is not possible with table arrays.
You can create a list of elements from the varargs by simply enclosing them in curly brackets, like so:
local tbl = {...} . This is now a table array.
With the return... command, you can return all of the received vararg parameters.
Note As mentioned earlier, the ... is also available as a named variable, arg , of type table , which
is the equivalent of {...} .
Parsing a List of Passed Parameters
Some functions have optional parameters, like so:
function addObjectAtPosition( [parent,] object, [x [, y [,position ] ] ] )
The values in square brackets are optional. In this function, the first parameter ( parent ) is optional, the
second ( object ) is not, and the third and fourth ( x and y ) are optional (but if either x or y is set,
the other must be set as well). The last parameter( position ) is optional.
Parsing this could get a bit difficult, but Lua makes it easy. Here's how it can be done. We know
that the parent and the object are table -type variables, x and y would be numeric, and the position
is a string. First, we check for the number of parameters passed—if only one is passed, we know it
must be the required parameter, object . If two are passed and the second one is of type table , the
 
Search WWH ::




Custom Search