Can you pass named parameters to a function?

Named parameters are convenient for a function with a lot of parameters, particularly if only a few are commonly used. There's no syntax for named parameters in Lua, but it's easy to support them. You pass a table and exploit the fact that it is not necessary to use extra parentheses in the case of a function passed a single table argument:

function named(t)
 local name = t.name or 'anonymous'
 local os = t.os or '<unknown>'
 local email = t.email or t.name..'@'..t.os
 ...
end named {name = 'bill', os = 'windows'}

Note the way that or works.

This style of passing named parameters involves creating a new table per call and so is not suitable for functions that will be called a large number of times.



Back