How To: Lua named arguments

From PGE Wiki
Jump to navigation Jump to search

Several programming languages let you create functions with named parameters called arguments. Named arguments are basically arguments that you can target using a name. As an example, in C# you can write this:

CalculateBMI(123, 64);

...but you can also write it like this:

CalculateBMI(weight: 123, height: 64);

By naming arguments, you improve readability. It also gives you more freedom as you're not forced to write arguments in a specific order and you may even leave arguments out (if they're marked as "optional".)

Named arguments in Lua

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 accept named arguments. The signature for those functions 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 named arguments:

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

You probably noticed that there are no parentheses used to call the function. If you only have one argument, and it's a table or string literal, the parentheses are optional.