lua-users home
lua-l archive

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


Rici Lake wrote:
> Doug Rogers wrote:
>> Wouldn't the __concat metamethod for strings handle that, though?
> .. on strings is a primitive; there is no __concat metamethod for
> strings. (And Lua takes advantage of that to implement multiple ..
> efficiently, so that  a .. b .. c is a single operation if a, b and c
> are all strings, avoiding the creation of a temporary string b .. c)

LRM5.1 sections 2.5.4 and 2.8 make it clear that that is the case, but
my brain simply refuses to remember such exceptions!

I'm curious about the efficiency gains. How often is this construct used
in time-critical code? I can understand that we would want
table.concat() to use tricks for efficiency gains, but I'm not so
convinced about violating the universality of metamethod __concat for a
.. b .. c. And my own sensibilities do not like the 'or type(opX) ==
"number"' part of the rule.

I must admit, though, that I can find only very contrived reasons for
replacing the built-in string concatenation operation.

> ... if you attempt to implement a
> __concat metamethod you will discover that numbers are coerced to
> strings before your metamethod is called.

I couldn't find code examples in the archives, so for those interested,
here's an example:

function concat(s,t) print(type(s)) print(type(t)) return s end
mt={__concat=concat}
function new(s) return setmetatable({val=s},mt) end
a=new('hey')
print(a .. 4)
-- table
-- number
-- table: 0x80845c0
print(4 .. a)
-- string
-- table
-- 4

The first print() works as expected. The second does not. The reference
manual states that the metamethod is called with (op1,op2), not with
(tostring(op1),op2).

Should this be considered a bug? If not, why not?

Doug

-- 
Doug Rogers   03CF-7D28-E4B1-9A56 Least 4x4+Binary magic square
Innovative Concepts, Inc.  703-893-2007 (x220)  www.innocon.com