3

When I have functions which take many arguments it's sometimes useful to pass a single table as an argument instead of many local variables.

function example_1(arg_one, arg_two, arg_three)
end

becomes

function example_2(arg_table)
    arg_table.arg_one, arg_table.arg_two, arg_table.arg_three
end

The problem is, when calling the function somewhere else in code, it's hard to remember what arg_table needs to consist of. There are plenty of code-completion plugins for many editors which will help you with remembering the arguments for the example_1 function, but not for example_2.

Is there any way to write the example_2 function with a table parameter in a way that is still a table, but also shows the necessary parameters for the function inside the ()?

something like this (which does not work):

function example_2(arg_table = {arg_one, arg_two, arg_three})

end
2
  • Start your function with assert(arg_table.arg_one ~= nil and arg_table.arg_two ~= nil and arg_table.arg_three ~= nil) Commented Sep 4, 2019 at 16:20
  • 4
    Why dont you simply unpack the table when calling the function and keep the function parameters? Commented Sep 4, 2019 at 16:57

2 Answers 2

1

Write your formal parameter list and documentation with separate parameters, as usual. Then document that if the first (and only) actual argument is a table, the effective arguments will be taken from the table using the formal parameter names as string keys.

Sign up to request clarification or add additional context in comments.

1 Comment

And, in the implementation, this is one of the few cases where I would ever change the value of an incoming parameter: arg_one, arg_two = arg_one.arg_one, arg_one.arg_two
0

You can keep the function parameters as they are and pass a table for convenience.

For example:

function example(arg_one, arg_two, arg_three)
    -- do stuff
end
local tbl = {"value for arg_one", "value for arg_two", "value for arg_three"}
example(table.unpack(tbl))

Note that this doesnt work for tables with named keys.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.