Reputation: 5877
The official documentation for metatables in Lua shows the following code:
Set = {}
function Set.new (t)
local set = {}
for _, l in ipairs(t) do set[l] = true end
return set
end
function Set.union (a,b)
local res = Set.new{}
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end
The syntax Set.new{}
is unclear to me. new
is a function and typically functions are called with parentheses ()
. What is this syntax and where is it documented in lua.org?
Upvotes: 1
Views: 568
Reputation: 5031
Lua allows the syntax of passing a string literal or table constructor into a function as its only param without needing to wrap it with parentheses, which in my opinion is hideous.
You will find it covered in Programming in Lua: 5 – Functions.
If the function has one single argument and this argument is either a literal string or a table constructor, then the parentheses are optional:
print "Hello World" <--> print("Hello World") dofile 'a.lua' <--> dofile ('a.lua') print [[a multi-line <--> print([[a multi-line message]] message]]) f{x=10, y=20} <--> f({x=10, y=20}) type{} <--> type({})
You can also find it in the refrence manaul Lua 5.4 Reference Manual: 3.4.10 – Function Calls
A call of the form f{fields} is syntactic sugar for f({fields}); that is, the argument list is a single new table. A call of the form f'string' (or f"string" or f[[string]]) is syntactic sugar for f('string'); that is, the argument list is a single literal string.
Upvotes: 4