Jump to content
  • Advertisement
Sign in to follow this  
Alpha_ProgDes

Named Arguments in Lua

This topic is 3697 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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


Link to post
Share on other sites
Advertisement
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
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!