lua

A copy of the Lua development repository
Log | Files | Refs | README

commit 8ba4523cccf59093543cec988b07957193d55692
parent 979ad95eb114d8d43f928b184f051ac0cfacedf7
Author: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date:   Wed, 10 Apr 2019 12:57:47 -0300

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

Diffstat:
Mlbaselib.c | 16+++++-----------
Mmanual/manual.of | 13+++++++++++--
Mtestes/calls.lua | 15---------------
3 files changed, 16 insertions(+), 28 deletions(-)

diff --git a/lbaselib.c b/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(); diff --git a/manual/manual.of b/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, @@ -8773,6 +8775,13 @@ like any other error when calling a finalizer.) @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. Moreover, it uses a different algorithm. diff --git a/testes/calls.lua b/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