lua-users home
lua-l archive

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


Monday, October 2, 2006, 1:29:16 PM, Sam Roberts wrote:

> On Mon, Oct 02, 2006 at 07:05:17AM -0400, John Belmonte wrote:
>> Doug Currie wrote:
>> > So, my request is that Lua 5.2 either
>> > - apply tostring() to non-string "%s" arguments of string.format(), or
>> > - add a string.format option that applies tostring() to its argument,
>> > and then performs the usual "%s" action.
>> 
>> I'd like to see the first implemented by having lua_tostring honor
>> __tostring, and perhaps adding a lua_rawtostring if there is really
>> demand for it.

> I don't think that can be done. Remember, lua_tostring converts the Lua
> value at the given index to a string.

> So, calling lua_tostring() on a value that had a __tostring metamethod
> would remove it from the stack, replacing it with a string. Some people
> already don't like auto-coercions between number and string, can you
> imagine the trouble it would cause to have your user-data auto-coerced
> to strings? :-(

Without arguing one way or the other about lua_tostring, to get my
first option:
- apply tostring() to non-string "%s" arguments of string.format()
the first couple lines of the 's' case of str_format() could be modified
as follows:

        case 's': {
          size_t l;
          const char *s;
          if (!lua_isstring(L, arg)) {
            lua_getglobal(L, "tostring");
            lua_pushvalue(L, arg);
            lua_call(L, 1, 1);
            lua_replace(L,arg);
          }
          s = luaL_checklstring(L, arg, &l);

This also replaces the userdata on the stack with a string, but since
this argument is consumed by string.format, it does not have the same
issues as lua_tostring().

Regards,

e

-- 
Doug Currie
Londonderry, NH