Gallaxhar
Gallaxhar

Reputation: 1036

Lua functions: how to use tables as function arguments and self-document the code

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

Upvotes: 3

Views: 2389

Answers (2)

Felix
Felix

Reputation: 2386

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.

Upvotes: 0

Tom Blodget
Tom Blodget

Reputation: 20772

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.

Upvotes: 1

Related Questions