Sign in to follow this  

Named Arguments in Lua

Recommended Posts

From Chapter 5.3 in Programming in Lua:
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,
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 this post

Link to post
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 this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this