If you need named arguments and default values, such as PHP or Python, you can call your function using the table constructor:
myfunction{a,b=3,c=2}
(This can be seen in many Lua places, such as the extended forms of the LuaSocket protocol modules and the constructors in IUPLua .)
The function itself may have the following signature:
function myfunction(t) setmetatable(t,{__index={b=7, c=5}}) local a, b, c = t[1] or ta, t[2] or tb, t[3] or tc -- function continues down here... end
Any values โโthat are not in the parameter table will be taken from the __index table in its metatet (see the metatables documentation ).
Of course, more complex parameter styles are possible using table and function constructors - you can write whatever you need. For example, here is a function that builds a function that takes named or positional argument tables from a table that defines parameter names and default values, and a function that uses a list of regular arguments.
As a function other than the language level, such calls can be modified to provide new behavior and semantics:
- Variables can be made to accept multiple names.
- Positional variables and keyword variables can be interspersed - and defining both can lead to priority (or cause an error).
- Variables without positioning with the keyword can be made, as well as anonymous positions related only to the position
- Strict table construction can be done by parsing a row
- The argument list can be used verbatim if the function is called with something other than table 1
Some useful functions for writing argument translators are unpack (switching to table.unpack in 5.2), setfenv (deprecated in 5.2 with the new _ENV construct), and select (which returns a single value from a list of given arguments or list length using '#' ).
Stuart P. Bentley May 16 '11 at 20:59 2011-05-16 20:59
source share