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: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.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:-- invalid code rename(old="temp.lua", new="temp1.lua") //here
Accordingly, we define rename with only one parameter and get the actual arguments from this parameter:rename{old="temp.lua", new="temp1.lua"} //and here
function rename (arg) return os.rename(arg.old, arg.new) end
Named Arguments in Lua
From Chapter 5.3 in Programming in Lua:
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.
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.
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"}).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement