diff options
author | Nat Goodspeed <nat@lindenlab.com> | 2024-06-07 21:43:41 -0400 |
---|---|---|
committer | Nat Goodspeed <nat@lindenlab.com> | 2024-06-07 21:43:41 -0400 |
commit | 486a6b189a3ea3fb2700718a64f574c3240fae7d (patch) | |
tree | 833c58498ae21cfe54dc50249614d19ff28c3daf /indra/llcommon/llsys.h | |
parent | af3a1b078e3575147d6ef30c03677d1e891b65e4 (diff) |
Introduce mapargs.lua, which defines the mapargs() function.
There are two conventions for Lua function calls. You can call a function with
positional arguments as usual:
f(1, 2, 3)
Lua makes it easy to handle omitted positional arguments: their values are nil.
But as in C++, positional arguments get harder to read when there are many, or
when you want to omit arguments other than the last ones.
Alternatively, using Lua syntactic sugar, you can pass a single argument which
is a table containing the desired function arguments. For this you can use
table constructor syntax to effect keyword arguments:
f{a=1, b=2, c=3}
A call passing keyword arguments is more readable because you explicitly
associate the parameter name with each argument value. Moreover, it gracefully
handles the case of multiple optional arguments. The reader need not be
concerned about parameters *not* being passed.
Now you're coding a Lua module with a number of functions. Some have numerous
or complicated arguments; some do not. For simplicity, you code the simple
functions to accept positional arguments, the more complicated functions to
accept the single-table argument style.
But how the bleep is a consumer of your module supposed to remember which
calling style to use for a given function?
mapargs() blurs the distinction, accepting either style. Coding a function
like this (where '...' is literal code, not documentation ellipsis):
function f(...)
local args = mapargs({'a', 'b', 'c'}, ...)
-- now use args.a, args.b, args.c
end
supports calls like:
f(1, 2, 3)
f{1, 2, 3}
f{c=3, a=1, b=2}
f{1, 2, c=3}
f{c=3, 1, 2} -- unlike Python!
In every call above, args.a == 1, args.b == 2, args.c == 3.
Moreover, omitting arguments (or explicitly passing nil, positionally or by
keyword) works correctly.
test_mapargs.lua exercises these cases.
Diffstat (limited to 'indra/llcommon/llsys.h')
0 files changed, 0 insertions, 0 deletions