lua-users home
lua-l archive

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


Would there be any reason not to allow ("abc"):upper() to be rewritten
as "abc":upper() ?  One complication is that the syntax is ambiguous
if the function call is used as or could be interpreted as a
statement.  The following is twice ambiguous:

  x = lower
        "abc"   -- ambiguous
  "abc":foo()  -- ambiguous

We'd like to avoid adding ambiguous syntax.  However, it could be
argued that the above doesn't add a new class of ambiguous syntax but
rather makes that existing class more consistent.  The above is just
syntactic sugar for

  x = lower
        ("abc")   -- ambiguous
  ("abc"):foo()  -- ambiguous

which itself is just as ambiguous, even under Lua 5.1.  The new rule
enforced by the parser becomes "there can be no line break between
prefixexp and args".  This new rule, unlike the old one, is invariant
under any translation between the two syntax forms above.

A prototype of how this might be implemented is given in the attached
patch (lua-5.1-string-paren-patch).  There is also a related patch [1]
that avoids spurious ambiguous syntax errors when the expression
cannot be interpreted as a statement.

Part of the reason for suggesting this was to analogously allow things
like ({3,2,1}):map(f) to be rewritten as {3,2,1}:map(f).  Now, even if
that could give no syntax error, it would normally still give a
runtime error.  That would be avoided if we could automatically assign
a default metatable with __index to constructed tables [3,*].  Lua
doesn't do that, at least in part, because it interferes with using
tables as maps/sets, but this problem can be avoided under the
__methindex (a.k.a. __mcall) proposal [2], which allows ":" to be
treated differently from ".".

[1] http://lua-users.org/lists/lua-l/2009-01/msg00052.html
[2] http://lua-users.org/lists/lua-l/2009-06/msg00394.html
[3] http://lua-users.org/lists/lua-l/2003-12/msg00384.html
[*] I was thinking of also adding a new table metamethod that
     would process fields (including nils) passed to the table constructor

Attachment: lua-5.1-string-paren-patch
Description: Binary data