Weird function "call" in Lua example from official docs

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?

>Solution :

Lua allows the hideous syntax of passing a string literal or table constructor into a function as its only param without needing to wrap it with parentheses.

you will find it coved 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({})

Leave a Reply