Bläddra i källkod

'print' does not call 'tostring' to format its arguments

Roberto Ierusalimschy 6 år sedan
förälder
incheckning
8ba4523ccc
3 ändrade filer med 16 tillägg och 28 borttagningar
  1. 5 11
      lbaselib.c
  2. 11 2
      manual/manual.of
  3. 0 15
      testes/calls.lua

+ 5 - 11
lbaselib.c

@@ -24,18 +24,12 @@
 static int luaB_print (lua_State *L) {
   int n = lua_gettop(L);  /* number of arguments */
   int i;
-  lua_getglobal(L, "tostring");
-  for (i=1; i<=n; i++) {
-    const char *s;
+  for (i = 1; i <= n; i++) {  /* for each argument */
     size_t l;
-    lua_pushvalue(L, -1);  /* function to be called */
-    lua_pushvalue(L, i);   /* value to print */
-    lua_call(L, 1, 1);
-    s = lua_tolstring(L, -1, &l);  /* get result */
-    if (s == NULL)
-      return luaL_error(L, "'tostring' must return a string to 'print'");
-    if (i>1) lua_writestring("\t", 1);
-    lua_writestring(s, l);
+    const char *s = luaL_tolstring(L, i, &l);  /* convert it to string */
+    if (i > 1)  /* not the first element? */
+      lua_writestring("\t", 1);  /* add a tab before it */
+    lua_writestring(s, l);  /* print it */
     lua_pop(L, 1);  /* pop result */
   }
   lua_writeline();

+ 11 - 2
manual/manual.of

@@ -6143,8 +6143,10 @@ In case of any error, @id{pcall} returns @false plus the error object.
 @LibEntry{print (@Cdots)|
 Receives any number of arguments
 and prints their values to @id{stdout},
-using the @Lid{tostring} function to convert each argument to a string.
-@id{print} is not intended for formatted output,
+converting each argument to a string
+following the same rules of @Lid{tostring}.
+
+The function @id{print} is not intended for formatted output,
 but only as a quick way to show a value,
 for instance for debugging.
 For complete control over the output,
@@ -8772,6 +8774,13 @@ like any other error when calling a finalizer.)
 @sect2{@title{Incompatibilities in the Libraries}
 @itemize{
 
+@item{
+The function @Lid{print} does not call @Lid{tostring}
+to format its arguments;
+instead, it has this functionality hardwired.
+You should use @id{__tostring} to modify how values are printed.
+}
+
 @item{
 The pseudo-random number generator used by the function @Lid{math.random}
 now starts with a somewhat random seed.

+ 0 - 15
testes/calls.lua

@@ -21,21 +21,6 @@ assert(type(f) == 'function')
 assert(not pcall(type))
 
 
-do    -- test error in 'print' too...
-  local tostring = _ENV.tostring
-
-  _ENV.tostring = nil
-  local st, msg = pcall(print, 1)
-  assert(st == false and string.find(msg, "attempt to call a nil value"))
-
-  _ENV.tostring = function () return {} end
-  local st, msg = pcall(print, 1)
-  assert(st == false and string.find(msg, "must return a string"))
-  
-  _ENV.tostring = tostring
-end
-
-
 -- testing local-function recursion
 fact = false
 do