lua-users home
lua-l archive

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


Take a look at the grammar specification:

prefixexp ::= var | functioncall | ‘(’ exp ‘)’
var ::=  Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name
exp ::=  nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp
tableconstructor ::= ‘{’ [fieldlist] ‘}’

So the `[2]` indexing operation must be part of a var symbol. That means that whatever precedes it must be a prefixexp. The tableconstructor {1,2,3} is a valid exp, but prefixexp can only take exps that are enclosed in parens. It's not very enlightening, but that's why you need parens to index into a tableconstructor—because the spec says so.

> On Jul 23, 2017, at 8:07 AM, temp212@gorodok.net wrote:
> 
> Why a new table needs to be put in parentheses to index it?
> a =  {4, 3, 2, 1} [2]   --error
> a = ({4, 3, 2, 1})[2]   --ok
> at the same time length operator # works either way.
> 
>