luaparenthesesbracketsargument-unpacking

Why do parentheses affect multiple-argument unpacking?


The string:find method in Lua can return multiple values: the start of the match and the end. I can then use unpacking to assign the start and the end to separate variables.

> text = 'ciao pollo mario'

> a, b = text:find('pollo') -- without parentheses
> a, b
6       10

But for some reason, putting parentheses around the find call messes up the unpacking:

> a, b = ( text:find('pollo') ) -- with parentheses
> a, b
6       nil

This is very sad since I use parentheses for code readability, like this:

> a, b = (
    text:find('pollo')
)

Why is this happening? I would expect that parentheses don't have any effect on the result!


Solution

  • Because Lua's syntax defines that expressions in parentheses can only be a single expression:

    exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp

    prefixexp ::= var | functioncall | ‘(’ exp ‘)’

    This is also mentioned in the manual:

    Lua 5.1-5.3 Any expression enclosed in parentheses always results in only one value.

    Lua 5.4 As a particular case, the syntax expects a single expression inside a parenthesized expression; therefore, adding parentheses around a multires expression forces it to produce exactly one result.