How To: Lua named arguments

From Moondust Wiki
Revision as of 11:59, 2 March 2017 by Fun2 (talk | contribs) (Added this page to the "How To" category.)
Jump to navigation Jump to search

In serveral programming languages offer a system, where you can have named argument in functions. Basically named arguments are arguments which you can target with a name.
As a example in C# you can write instead of this:

CalculateBMI(123, 64);

you can write this:

CalculateBMI(weight: 123, height: 64);

This not only improves readablity, but it also gives you more freedom. You're not forced to write the arguments in a specific order and you can even let some arguments out (if they are marked as "optional")

Named arguments in lua

So lua doesn't offer such a system directly. However, you can use a table to apply this technique. In LunaLua there are several functions which accepts named arguments. The signature for those function are always the same:

function foo(table namedArgs)

To call this function you can write this:

foo {bar = "Hi", baz = 4}

or you can use an alternative order:

foo {baz = 4, bar = "Hi"}
foo {qux = 10, baz = 4, bar = "Hi"}
foo {bar = "Hi", qux = 10, baz = 4}

In this example foo can accept as a named argument:

  • bar (A string value)
  • baz (A number value)
  • qux (A number value [Optional value])

You probably noticed that there are no round brackets used to call the function. You only need round brackets if you have more than one argument.