avoid using 'fputs' in 'print' to avoid problems with embedded zeros

This commit is contained in:
Roberto Ierusalimschy 2009-02-06 16:38:47 -02:00
parent cbf0c7a103
commit 53db607963
1 changed files with 12 additions and 6 deletions

View File

@ -1,5 +1,5 @@
/* /*
** $Id: lbaselib.c,v 1.207 2008/07/03 14:23:35 roberto Exp roberto $ ** $Id: lbaselib.c,v 1.208 2008/07/11 17:51:01 roberto Exp roberto $
** Basic library ** Basic library
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
@ -24,27 +24,33 @@
/* /*
** If your system does not support `stdout', you can just remove this function. ** If your system does not support `stdout', you can just remove this function.
** If you need, you can define your own `print' function, following this ** If you need, you can define your own `print' function, following this
** model but changing `fputs' to put the strings at a proper place ** model but changing `writestring' to put the strings at a proper place
** (a console window or a log file, for instance). ** (a console window or a log file, for instance).
*/ */
static void writestring (const char *s, size_t l) {
fwrite(s, sizeof(char), l, stdout);
}
static int luaB_print (lua_State *L) { static int luaB_print (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */ int n = lua_gettop(L); /* number of arguments */
int i; int i;
lua_getglobal(L, "tostring"); lua_getglobal(L, "tostring");
for (i=1; i<=n; i++) { for (i=1; i<=n; i++) {
const char *s; const char *s;
size_t l;
lua_pushvalue(L, -1); /* function to be called */ lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */ lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1); lua_call(L, 1, 1);
s = lua_tostring(L, -1); /* get result */ s = lua_tolstring(L, -1, &l); /* get result */
if (s == NULL) if (s == NULL)
return luaL_error(L, LUA_QL("tostring") " must return a string to " return luaL_error(L, LUA_QL("tostring") " must return a string to "
LUA_QL("print")); LUA_QL("print"));
if (i>1) fputs("\t", stdout); if (i>1) writestring("\t", 1);
fputs(s, stdout); writestring(s, l);
lua_pop(L, 1); /* pop result */ lua_pop(L, 1); /* pop result */
} }
fputs("\n", stdout); writestring("\n", 1);
return 0; return 0;
} }