Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

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
like image 310
Gallaxhar Avatar asked Feb 05 '26 10:02

Gallaxhar


1 Answers

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.

like image 188
Tom Blodget Avatar answered Feb 08 '26 00:02

Tom Blodget



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!