From 5b6b2f98b7981d7b3ed05115f53a44c0fcfd750d Mon Sep 17 00:00:00 2001 From: philip Date: Sun, 20 Sep 2020 10:57:09 -0400 Subject: [PATCH] Make round tripping work for lua53 and floats --- app/modules/node.c | 24 ++++++++++++++++++++++++ app/modules/sjson.c | 13 +++++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/app/modules/node.c b/app/modules/node.c index 47e162c3..6567ef89 100644 --- a/app/modules/node.c +++ b/app/modules/node.c @@ -643,6 +643,28 @@ static int node_writercr (lua_State *L) { lua_pushinteger(L, n); return 1; } + +static int node_int2float(lua_State *L) { + union { + lua_Integer i; + lua_Float f; + } u; + + u.i = luaL_checkinteger(L, 1); + lua_pushnumber(L, u.f); + return 1; +} + +static int node_float2int(lua_State *L) { + union { + lua_Integer i; + lua_Float f; + } u; + + u.f = luaL_checknumber(L, 1); + lua_pushinteger(L, u.i); + return 1; +} #endif // Lua: n = node.LFS.reload(lfsimage) @@ -915,6 +937,8 @@ LROT_BEGIN(node, NULL, 0) #endif #ifdef DEVELOPMENT_TOOLS LROT_FUNCENTRY( osprint, node_osprint ) + LROT_FUNCENTRY( int2float, node_int2float ) + LROT_FUNCENTRY( float2int, node_float2int ) #endif LROT_FUNCENTRY( getpartitiontable, node_getpartitiontable ) LROT_FUNCENTRY( setpartitiontable, node_setpartitiontable ) diff --git a/app/modules/sjson.c b/app/modules/sjson.c index 2dc3ca08..8e2b2384 100644 --- a/app/modules/sjson.c +++ b/app/modules/sjson.c @@ -18,6 +18,8 @@ #define DBG_PRINTF(...) +#define SJSON_FLOAT_FMT ((sizeof(lua_Float) == 8) ? "%.19g" : "%.9g") + typedef struct { jsonsl_t jsn; int result_ref; @@ -720,10 +722,13 @@ static void encode_lua_object(lua_State *L, ENC_DATA *data, int argno, const cha case LUA_TNUMBER: { lua_pushvalue(L, argno); - size_t len; - const char *str = lua_tolstring(L, -1, &len); - char value[len + 1]; - strcpy(value, str); + char value[50]; + + if (lua_isinteger(L, -1)) { + l_sprintf(value, sizeof(value), LUA_INTEGER_FMT, lua_tointeger(L, -1)); + } else { + l_sprintf(value, sizeof(value), SJSON_FLOAT_FMT, lua_tonumber(L, -1)); + } lua_pop(L, 1); if (strcmp(value, "-Infinity") == 0 || strcmp(value, "NaN") == 0 || strcmp(value, "Infinity") == 0) { luaL_addstring(&b, "null"); // According to ECMA-262 section 24.5.2 Note 4