lua-users home
lua-l archive

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

a = 'a'
b = 'b'

function string:xxx()
 return '['..self..']'


If you try the above you have your answer.

So, "xxx":sub() seems a quite reasonable request. Actually, this was the first thing I had tried when still learning the basics of Lua before I found out I needed to do ( ): for it work with string literals.

-----Original Message----- From: Andrew Starks
Sent: Wednesday, May 06, 2015 7:27 PM
To: Lua mailing list
Subject: Re: metatables for strings?

On Wed, May 6, 2015 at 11:13 AM, Luiz Henrique de Figueiredo
<> wrote:
>> PS. I still like syntax "hello":sub(1, 4)

I always wondered: is there a reason why this syntax is not supported?

Because to allow it in general would require unbounded lookahead.
Consider for instance:
        "x".."x".."x".."x".."x".."x".."x".."x".."x".."x".."x":sub(1, 4)

The current solution with parentheses solves this and is fully general.
It's probaly easy to allow just this syntax <string literal> : <function call>,
but not general enough.

Is the ':' operator part of precedence? Meaning, is there a precedence
that can be used to generally say "concatenation has higher precedence
than `:`". Forgive me if this is a dumb question.

I'm motivated to ask it because requiring parentheses for what you
described (or actually just stating that `:sub(4)` is only called on
the final `"x"` string) is understandable, to me. Also, for my use
case, I am not likely to run into that, because I'm using format,
which is often used as a more flexible substitution for concatenation.