lua-users home
lua-l archive

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

On 2014-03-25 8:11 AM, "Luiz Henrique de Figueiredo" <> wrote:
> > The API and VM instructions, like print(), invoke__tostring() automatically.
> The core and the API do not call __tostring at all.
> print calls tostring which in turn calls __tostring.
> The libraries may call __tostring via luaL_tolstring.
> Bottom line: __tostring is a non-core metamethod.

This has been a thorn in my side when implementing objects which pretend to be strings. (In my case, to retrieve strings from a config file transparently; the same trick might also be used to implement "ropes".) By applying metamethods such as __tostring and __concat to the objects, they could be used as if they were strings anywhere - except when passing them to a C library.

In my opinion a limited amount of coercion is welcome, mainly when it's implied from context. I hate having to add tonumber() and tostring() everywhere, and Lua 5.2 using tostring() for %s format was a very welcome change. I also feel that metamethods should make it possible for one object to mimic another in every situation except perhaps explicitly asking its type.

Particularly I feel __tostring and __tonumber should be invoked:
-by string.format with formats that expect strings/numbers
-by tostring() and tonumber()
-by table.concat
-by .. operator if the operands don't have __concat
-by math operators
-by lua_tostring/lua_tonumber and related (and lua_isstring/lua_tonumber should return true if __tostring is present)

Maybe some other situations as well that don't come to mind right now.