Make round tripping work for lua53 and floats

This commit is contained in:
philip 2020-09-20 10:57:09 -04:00 committed by Nathaniel Wesley Filardo
parent e9c4bb74d3
commit 5b6b2f98b7
2 changed files with 33 additions and 4 deletions

View File

@ -643,6 +643,28 @@ static int node_writercr (lua_State *L) {
lua_pushinteger(L, n); lua_pushinteger(L, n);
return 1; 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 #endif
// Lua: n = node.LFS.reload(lfsimage) // Lua: n = node.LFS.reload(lfsimage)
@ -915,6 +937,8 @@ LROT_BEGIN(node, NULL, 0)
#endif #endif
#ifdef DEVELOPMENT_TOOLS #ifdef DEVELOPMENT_TOOLS
LROT_FUNCENTRY( osprint, node_osprint ) LROT_FUNCENTRY( osprint, node_osprint )
LROT_FUNCENTRY( int2float, node_int2float )
LROT_FUNCENTRY( float2int, node_float2int )
#endif #endif
LROT_FUNCENTRY( getpartitiontable, node_getpartitiontable ) LROT_FUNCENTRY( getpartitiontable, node_getpartitiontable )
LROT_FUNCENTRY( setpartitiontable, node_setpartitiontable ) LROT_FUNCENTRY( setpartitiontable, node_setpartitiontable )

View File

@ -18,6 +18,8 @@
#define DBG_PRINTF(...) #define DBG_PRINTF(...)
#define SJSON_FLOAT_FMT ((sizeof(lua_Float) == 8) ? "%.19g" : "%.9g")
typedef struct { typedef struct {
jsonsl_t jsn; jsonsl_t jsn;
int result_ref; 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: case LUA_TNUMBER:
{ {
lua_pushvalue(L, argno); lua_pushvalue(L, argno);
size_t len; char value[50];
const char *str = lua_tolstring(L, -1, &len);
char value[len + 1]; if (lua_isinteger(L, -1)) {
strcpy(value, str); 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); lua_pop(L, 1);
if (strcmp(value, "-Infinity") == 0 || strcmp(value, "NaN") == 0 || strcmp(value, "Infinity") == 0) { 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 luaL_addstring(&b, "null"); // According to ECMA-262 section 24.5.2 Note 4