Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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({})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading