lua-users home
lua-l archive

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


Ben Sunshine-Hill wrote:
On 7/20/05, Ignacio Burgueño <ignacio@tecnolink.com.uy> wrote:

Hi. I'd like to modify the parser so I could concatenate strings using '+'.
I guess that I need to modify lparser.c, function subexpr. My initial
attempt was to change the operand from OPR_ADD to OPR_CONCAT, but only if
the operands are strings. This last part is what I couldn't figure out. Is
this possible ?

Thanks in advance,
Ignacio


No, it isn't possible. Consider this construction:

function foo(a,b)
    return a+b
end

Q: Are a and b strings or not? A: There's no way to know. This is
what's known as "static type analysis", and is only possible for
dynamically typed languages in special cases.

There's a good reason why + doesn't concatenate in Lua: to avoid
accidentally concatenating when you really meant to add. Since numbers
can be used in a string context and vice versa, this would generate
quite a few problems. Stick to .. for concatenation.

This is an old-time issue from Javascript, which overloads '+' to do both concat and numeric add. It is solvable by having certain rules about when to do concat and when to do add. For instance, Javascript will use concat if either operand is a string. Otherwise it will try to convert both operands to numbers and do an add (from the ECMAScript 3 spec). I'm not saying that is a good rule, and it certainly does get you into trouble. But it is at least a consistent rule :-)

Adding this logic to Lua would be very easy. You would simply go into lvm.c and change the Arith() function to test for strings if op is TM_ADD and then jump out to luaV_concat() if so. This adds a bit of logic to Arith() which slows down every arithmetic operation. But, at worst, this is something like:

    if (op == TM_ADD &&
            (ttype(rb) == LUA_TSTRING || ttype(rc) == LUA_TSTRING))
        luaV_concat(...);

For all ops other than ADD this adds one integer compare and for ADD it adds an additional one or two integer compares. Not bad for what it gives you IMHO...

--
chris marrin                ,""$,
chris@marrin.com          b`    $                             ,,.
                        mP     b'                            , 1$'
        ,.`           ,b`    ,`                              :$$'
     ,|`             mP    ,`                                       ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`
"As a general rule,don't solve puzzles that open portals to Hell"'