Named Arguments in Lua

Started by
2 comments, last by Alpha_ProgDes 15 years, 9 months ago
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.

Beginner in Game Development?  Read here. And read here.

 

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.
Million-to-one chances occur nine times out of ten!
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"}).
Ahhhhh. I see. Thanks I couldn't tell those were brackets.... oops.

Beginner in Game Development?  Read here. And read here.

 

This topic is closed to new replies.

Advertisement