# Named Arguments in Lua

## Recommended Posts

From Chapter 5.3 in Programming in Lua:
Quote:
 The parameter passing mechanism in Lua is positional: When we call a function, arguments match parameters by their positions. The first argument gives the value to the first parameter, and so on. Sometimes, however, it is useful to specify the arguments by name. To illustrate this point, let us consider the function rename (from the os library), which renames a file. Quite often, we forget which name comes first, the new or the old; therefore, we may want to redefine this function to receive its two arguments by name:  -- invalid code rename(old="temp.lua", new="temp1.lua") //here Lua has no direct support for that syntax, but we can have the same final effect, with a small syntax change. The idea here is to pack all arguments into a table and use that table as the only argument to the function. The special syntax that Lua provides for function calls, with just one table constructor as argument, helps the trick:  rename{old="temp.lua", new="temp1.lua"} //and here Accordingly, we define rename with only one parameter and get the actual arguments from this parameter:  function rename (arg) return os.rename(arg.old, arg.new) end
I'm not understanding where the change is made or if a change was made at all. Obviously something went over my head, but I don't what it was.

##### Share on other sites
The parenthesis changed to curly brackets. Which is syntactic sugar for

rename( {old="temp.lua", new="temp1.lua"} )

i.e., a single table as argument, as if it were:

tmp = {old="temp.lua", new="temp1.lua"}
rename( tmp )

and that table has two string members, old and new.

##### Share on other sites
The second rename has {} instead of (). Calling a function using this syntax passes it a single table argument. It is shorthand for func({old="temp.lua", new="temp1.lua"}).

##### Share on other sites
Ahhhhh. I see. Thanks I couldn't tell those were brackets.... oops.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628395
• Total Posts
2982437

• 10
• 9
• 19
• 24
• 10