lua-users home
lua-l archive

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



On 29-Jan-07, at 8:12 AM, Doug Rogers wrote:

Rici Lake wrote:

Mark Hamburg wrote:
I have to say that the automatic coercion between strings and numbers
in the Lua API is one of my least favorite features. ...
Furthermore, it would be nice if luaL_tostring was essentially the
same as invoking tostring ... so that it could handle arbitrary objects.

I agree, wholeheartedly.

Sorry for the late entry, but I just wanted to cast my vote along with
Mark and Rici.

Perhaps there are some subtle side effects I'm missing. I have enjoyed
the benefits of the coercion when I'm typing at the interpreter, but
often that amounts to simple things like:

print('n = ' .. n)

I would not mind having to type:

print('n = ' .. tostring(n))

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)

However, one of the annoyances of automatic coercion, which has been mentioned a couple of times, is that if you attempt to implement a __concat metamethod you will discover that numbers are coerced to strings before your metamethod is called.

The __tostring metamethod is not used by the Lua VM or the API; it is implemented by the tostring() base library function (and consequently used by print(), which calls tostring(), but not by io.write().) Mark's suggestion of adding a luaL_tostring() function which invokes the __tostring metamethod might encourage more consistent behaviour.