This post was originally published at Tutorial: Variable Arguments to Functions

In a previous tutorial, Passing Data To/From Functions, we illustrated how to pass arguments to function calls. In this tutorial we’ll expand upon the concept and outline other ways to handle optional arguments.

Varying Number of Arguments

Sometimes a function may need to accept a variable number of arguments. Lua accommodates for this with the variable arguments (...) syntax. Consider the following function which takes an unspecified amount of numerical arguments and adds them together into one sum:

Notice how Lua uses 3 consecutive periods (...) to indicate a varying number of arguments, and note that this is not the special “ellipsis” character (…). Once inside the function, this produces a table called arg which is a numerically-indexed table (array) that can be iterated over to access each of the arguments:

Handling Argument Types

In the example function above, we expect each argument to be number, so we handle them accordingly by adding them together. However, we might need to deal with a mixed set of arguments including numbers, strings, tables, or even other functions. To help verify each argument, Lua provides the simple type() function which can be used to detect arguments of a specific type and react accordingly.

Let’s build a custom string.join utility function which can be included as part of the string library. To keep it object-oriented like the other string functions, we’ll pass in the string to append to as the first argument. We’ll also pass in a separator string to make the returned value more readable.

Alternatively, since this was set up to be object-oriented, we could have used:

In this second example, the : colon operator causes the function to pass in itself (cookieIngredients) as the real first argument.

Conclusion

As exhibited, functions which accept a variable number arguments can be a potent tool in your code arsenal. Further enhancing these functions to filter and handle specific type(s) of arguments can be especially useful when dealing with input arguments which are not assured to be of a predictable type or in a particular order.

Link:  

This post was originally published at Tutorial: Variable Arguments to Functions