Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
75 lines (55 sloc) 2.42 KB
Patch string.format %s to use __tostring
Author: Doug Currie
Derived from:, posted 3 Oct 2006
Updated: 17 May 2012 by
(i) to apply against Lua 5.1.5
(ii) for clearer error messages, only try to call tostring when it's non-nil
Description from <>
Subject: Re: 5.2 feature list?
From: Doug Currie <doug.currie@...>
Date: Sun, 1 Oct 2006 19:06:05 -0400
Monday, September 11, 2006, 12:32:09 PM, Roberto Ierusalimschy wrote:
>> i have seen some lua 5.2 feature requests. is there an "official" place
>> where the feature requests are stored/tracked?
> Only the list itself.
Here is a proposal for 5.2...
It was a surprise to me that string.format()'s option "%s" did not
apply tostring() to its arguments as print() does.
This would make formatted output using, e.g., loadable numerics
libraries like decNumber, much more convenient. Of course, it would
work with any userdata or class that implemented __tostring.
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.
If the second approach is preferred, I am not particular to any
specific character to specify this format option, though I recommend
"%m" (use Metatable's __tostring) or "%y" (stringifY) -- neither of
these is in common usage with printf as far as I know, unlike "%o"
(Object) and "%S" (wide String).
Doug Currie
Londonderry, NH
diff -urN lua-5.1.5.orig/src/lstrlib.c lua-5.1.5/src/lstrlib.c
--- lua-5.1.5.orig/src/lstrlib.c 2010-05-14 11:34:19.000000000 -0400
+++ lua-5.1.5/src/lstrlib.c 2012-05-17 12:30:02.321718857 -0400
@@ -798,7 +798,16 @@
case 's': {
size_t l;
- const char *s = luaL_checklstring(L, arg, &l);
+ const char *s;
+ if (!lua_isstring(L, arg)) {
+ lua_getglobal(L, "tostring");
+ if (!lua_isnil(L, -1)) {
+ lua_pushvalue(L, arg);
+ lua_call(L, 1, 1);
+ lua_replace(L, arg);
+ }
+ }
+ s = luaL_checklstring(L, arg, &l);
if (!strchr(form, '.') && l >= 100) {
/* no precision and string is too long to be formatted;
keep original string */