lua-users home
lua-l archive

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


On Wed, Jun 13, 2012 at 2:14 PM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>> Concerning (2): not all types have metatables so boolean is still
>> somewhat of a problem then. (I can live with it.)
>
> We can use the metatables for strings (if at least one argument is
> a string)! This already works both in 5.1 and 5.2:
>
> mt = getmetatable("")
>
> mt.__concat = function (a,b)
>   return tostring(a) .. tostring(b)
> end
>
> print("result: " .. {})     --> result: table: 0x8172130
> print(false .. " x " .. true)  --> false x true

It should be noted that defining __add, __mul, etc. for strings would
maybe complicate libraries like lpeg. Any attempt to implicitly coerce
a string would require having the string on the right side of the
binary operator.

[Unless the string metamethods are "smart" and, if they don't know
what to do with a userdatum, call the right operand's metamethod, if
available. Or, maybe Lua could define an ordering for which metamethod
it chooses based on type: userdata's metamethods are used first, then
tables, then maybe everything else.]

For me, I would be a much happier Lua coder if coercion to strings
were automatic in more places. Concatenation, table.concat,
string.format("%s"), and others should all call (__)tostring
(metamethod), IMO. As for Lua core string <-> number coercions, I'd be
happy to see that go.

-- 
- Patrick Donnelly