lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Using Lua 5.3.
> 
> Code:
> 
> return { 1 } [1]
> 
> Result:
> 
> <eof> expected near '['
> 
> Code:
> 
> return ( { 1 } ) [1]
> 
> Result:
> 
> 1
> 
> The question is, why is the first version not accepted? I am not
> asking for an explanation why the details are such and such, but
> rather for a rationale, if there is one, that a table "literal"
> (constructor) should not appear in some expressions unless it is
> wrapped in parentheses.

For regularity, what can come before [exp] is the same stuff that
can come before (explist), forming function calls. Allowing {1}[1]
would also allow {1}(1), which being a function call could be
used as a statement:

  a = b
  {1}(1)     -- "calling" table {1}

That would create another ambiguity in the grammar, similar to the
(already present) ambiguity with parentheses:

  a = b
  (print)(1)     -- calling print or calling b?

We chose to reduce ambiguities.

Note too that all other "literals" also cannot be used in that position:

  4[1];  "hello"[1];  true[1];  nil[1]

But, in the end, it all boils down to taste.

-- Roberto