luamanual

How assignments can start with an open parenthesis in Lua?


While reading the Lua manual I came upon this part:


Both function calls and assignments can start with an open parenthesis. This possibility leads to an ambiguity in Lua's grammar. Consider the following fragment:

a = b + c
(print or io.write)('done')

The grammar could see this fragment in two ways:

a = b + c(print or io.write)('done')
a = b + c; (print or io.write)('done')

From the example I can understand that function calls can start with an open parentheses:

a = b + c(print or io.write)('done')
         ^

But even thinking for hours I'm unable to figure out how assignments can start with an open parenthesis and how does it relates to the above example(the 2nd line).

Could anyone please explain me clearly, the meaning of that sentence with an example?


Solution

  • Take a look at The Complete Syntax of Lua.

    Assignment is defined as

    varlist ‘=’ explist
    

    And varlist is defined as

    varlist := var {‘,’ var}
    var := Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name 
    prefixexp := var | ‘(’ exp ‘)’
    exp := prefixexp
    

    This is the same as functioncall, since it can start with prefixexp, and a prefixexp can start with an open parenthesis.

    functioncall ::=  prefixexp args | prefixexp ‘:’ Name args 
    

    So we can build a very simple example:

    a = {}
    (a).b = false