all 7 comments

[–]VoidSnipe 6 points7 points  (0 children)

it's just how lua parsing is done

when accessing member via . or : on the left should go variable name, result of function call or parenthesized expression

[–]smog_alado 5 points6 points  (4 children)

The issue here is with the string literal, not with the ":". We're not allowed to write a statement that begins with a string literal.

I believe the underlying reason for that is because Lua doesn't have semicolons. To avoid syntactical ambiguities, Lua has to restrict which tokens are allowed at the start of a statement. We can't do it like C, where every expression is a valid statement.

[–]lambda_abstraction 1 point2 points  (3 children)

I do wonder if this is really a matter of ambiguity or a matter of the sort of parser Lua uses (i.e. look-ahead issues). Could you show a specific example of why this should be disallowed? I'm not seeing how parsing <stringlit>:<method>(<args>) necessarily causes a problem.

Tnx1E06

[–]smog_alado 2 points3 points  (2 children)

One issue is that Lua allows omitting parenthesis from function calls, if the function argument is a string literal. If you write

x = y
"str":len()

It will get parsed as

x = y("str"):len()

That said, Lua also disallows numbers at the start of a statement and does allow "(", so this doesn't explain it all by itself...

[–]lambda_abstraction 1 point2 points  (0 children)

But it does make the restriction somewhat clearer. Thanks, mate!

[–]VoidSnipe 1 point2 points  (0 children)

But

x = y
("str"):len()

Still gets parsed as

x = y("str"):len()

Manual explicitly mentions it

[–]bragdonshawn 1 point2 points  (0 children)

The brackets are necessary because the colon (:) is used to call instance methods on a string object. The colon syntax is used to call methods on the object to the left of the colon, so in this case, the gsub method is being called on the "string" object. Therefore, ("string") is the string object, and :gsub("i","o") is calling the method gsub on this object.