One of the key advantages of functions is that they allow a piece of code to be written then called repeatedly. This is accomplished by allowing arguments to be passed to functions, then have the function work with those arguments to produce the desired output.
Most functions are defined to accept a fixed number of arguments. When values are passed to the function they are taken positionally and assigned to the variable name for the corresponding argument. When arguments are passed into a function, they become locally-scoped within the function, just like variables that are defined inside the function definition, which allows Lua to support nesting and recursive functions.
Lua is quite forgiving regarding values passed to functions, when a function call contains fewer values than arguments it simply assigns nil to the unused variables. When too many values are passed, it simply ignore them extra values. For example, the following function definition expects 2 values to be passed into the function when it is called:
local test = function(a, b)
print(a)
print(b)
end
Let's now call this function:
print(test(1, 2))
which produces the output:
1
2
·
Ok, as expected. Let's now try calling the function with a single argument:
print(test(1))
which produces the output:
1
nil
·
Whereas many languages will raise an error when a function is called with the incorrect number of arguments, Lua simply assigns nil to unused variables. Finally, let's try passing extra arguments to our function:
print(test(1, 2, 3))
which produces the output:
1
2
·
Again, no error was raised, and the extra argument was simply ignored.