lua-users home
lua-l archive

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



On 2-Oct-06, at 6:05 AM, 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.

--John


I don't think that's really necessary. It can easily be written (although the following code has not actually been tested):

/* If possible, pushes onto the stack the string coercion of the object
   at stack or pseudo index obj, and returns a pointer to the C string.
If plen is not NULL, stores the length of the returned string in plen.

   If the indicated object cannot be coerced to a string, returns
   NULL, does not alter plen, and does not alter the stack.
 */
const char *my_pushstringvalue (luaState *L, int obj, size_t *plen) {
  switch (lua_type(L, obj)) {
    case LUA_TSTRING:
    case LUA_TNUMBER:
      lua_pushvalue(L, obj);
    default: {
      if (0 == luaL_callmeta(L, obj, "__string"))
        return NULL;
    }
  }
  return lua_tolstring(L, -1, plen);
}

/* If the object at stack or pseudo index obj is a string, returns
   a pointer to the C string and, if plen is not NULL, stores the
   length of the string in plen. Otherwise, returns NULL and does
   not alter plen.
 */
const char *my_rawtostring (lua_State *L, int obj, size_t *plen) {
  if (lua_type(L, obj) == LUA_TSTRING)
    return lua_tolstring(L, obj, plen);
  else
    return NULL;
}