Reputation: 58
I recently saw a new method, at least to me, for calling functions in Lua and that is by using the curly braces {}, certainly if the parameter was a table. Take this function as an example of what I want to examine:
function test(table)
for _, i in pairs(table) do
print(i);
end
end
test{"What", "is", "the", "difference?"};
In calling the function test(), we used the curly braces "{}" instead of the normal braces "()".
So my questions go, what is the difference between those two? Which is better in performance? When should I use one rather than the other? Why was such a way like this created while the normal braces did the job?
Upvotes: 0
Views: 1579
Reputation: 28960
Lua provides two syntactic sugars for function arguments. Their purpose is convenience only.
You may choose whatever you (and your colleagues) prefer in terms of convenience , readability and your software design. Performance-wise there is no difference.
If your only argument is a single literal string or a single new table (table constructor!) you may omit the parenthesis.
From the Lua reference manual:
Arguments have the following syntax:
args ::= `(´ [explist] `)´
args ::= tableconstructor
args ::= String
All argument expressions are evaluated before the call. A call of the form
f{fields}
is syntactic sugar forf({fields})
; that is, the argument list is a single new table. A call of the formf'string'
(orf"string"
orf[[string]])
is syntactic sugar forf('string')
; that is, the argument list is a single literal string.
Upvotes: 5