From e3ce88c9e850b7e79751083014699c5eae1bff31 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Wed, 23 Oct 2024 17:16:17 -0300 Subject: New function 'lua_numbertostrbuff' It converts a Lua number to a string in a buffer, without creating a new Lua string. --- liolib.c | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) (limited to 'liolib.c') diff --git a/liolib.c b/liolib.c index 17522bb2..98ff3d0d 100644 --- a/liolib.c +++ b/liolib.c @@ -665,20 +665,16 @@ static int g_write (lua_State *L, FILE *f, int arg) { int status = 1; errno = 0; for (; nargs--; arg++) { - if (lua_type(L, arg) == LUA_TNUMBER) { - /* optimization: could be done exactly as for strings */ - int len = lua_isinteger(L, arg) - ? fprintf(f, LUA_INTEGER_FMT, - (LUAI_UACINT)lua_tointeger(L, arg)) - : fprintf(f, LUA_NUMBER_FMT, - (LUAI_UACNUMBER)lua_tonumber(L, arg)); - status = status && (len > 0); - } - else { - size_t l; - const char *s = luaL_checklstring(L, arg, &l); - status = status && (fwrite(s, sizeof(char), l, f) == l); + char buff[LUA_N2SBUFFSZ]; + const char *s; + size_t len = lua_numbertostrbuff(L, arg, buff); /* try as a number */ + if (len > 0) { /* did conversion work (value was a number)? */ + s = buff; + len--; } + else /* must be a string */ + s = luaL_checklstring(L, arg, &len); + status = status && (fwrite(s, sizeof(char), len, f) == len); } if (l_likely(status)) return 1; /* file handle already on stack top */ -- cgit v1.2.3-55-g6feb