views:

410

answers:

1

Lua has a really nice no-parenthesis call syntax that coupled with function closures allow me to write the following

local tag = 1
function test(obj)
    return 
     function(str)
      return 
      function (tbl)
       tbl.objtag = tag
       tbl.objname = str
       return tbl
      end
     end

end
test (tag) "def"
{
}

test tag "def" --error
{
}

However, if I remove the parenthesis around (tag), it results in a compile error. So why does Lua allow no-parenthesis parameters (i.e. "def") and not no-parenthesis var (table in this case) parameters?

+3  A: 

From Programming in Lua:

If the function has one single argument and this argument is either a literal string or a table constructor, then the parentheses are optional:

My understanding of your above situation is that tag is a local variable (which is neither a literal string nor a table constructor), so test(tag) always requires parentheses. You don't need parentheses around "def" because test(tag) returns a function which accepts a single string, and that function is immediately applied to "def".

Mark Rushakoff
Thank you for that explanation. I was so close to a full fledged DSL...
jameszhao00
Is there any reason you couldn't run the input to the DSL through some sort of "preprocessor" to put parentheses around everything?
Mark Rushakoff
Yea found metalua. It does what you're describing.
jameszhao00
This has come up in the mailing list a couple of times. It usually starts by wondering why literal numbers aren't included. IIRC, there are parsing edge cases where the benefits to some don't outweigh the costs to everyone else. The benefits in the case of table c-tors and literal strings are pretty clear, especially in the early Lua use-case of data description languages.
RBerteig