# HG changeset patch # User jbe # Date 1406771133 -7200 # Node ID 004d2d50419e619307196825fde1a710d3c1f58a # Parent 88b613f5bc22fcbf5b7044357470af8418433ce1 Allow direct usage of json.null values in JSON library (for writing, not reading) diff -r 88b613f5bc22 -r 004d2d50419e libraries/json/json.c --- a/libraries/json/json.c Thu Jul 31 03:19:09 2014 +0200 +++ b/libraries/json/json.c Thu Jul 31 03:45:33 2014 +0200 @@ -36,6 +36,12 @@ JSON_REGENT arraymt; // metatable for JSON arrays } json_registry; +// returns the string "": +static int json_nullmark_tostring(lua_State *L) { + lua_pushliteral(L, ""); + return 1; +} + // marks a Lua table as JSON object or JSON array: // (returns its modified argument or a new table if argument is nil) static int json_mark(lua_State *L, JSON_REGPOINTER mt) { @@ -739,6 +745,10 @@ int needsep = 0; lua_Integer idx; lua_settop(L, 1); + if (json_isnullmark(L, 1)) { + lua_pushnil(L); + lua_replace(L, 1); + } switch (lua_type(L, 1)) { case LUA_TNIL: lua_pushliteral(L, "null"); @@ -889,6 +899,12 @@ {NULL, NULL} }; +// metamethods for JSON null marker: +static const struct luaL_Reg json_nullmark_metamethods[] = { + {"__tostring", json_nullmark_tostring}, + {NULL, NULL} +}; + // initializes json library: int luaopen_json(lua_State *L) { // empty stack: @@ -918,7 +934,12 @@ lua_rawset(L, -3); lua_setmetatable(L, -2); json_regstore(L, shadowtbl); - // return library module stored on lowest stack position: - lua_settop(L, 1); + // set metatable of null marker and make it available through library module: + json_pushnullmark(L); + lua_newtable(L); + luaL_setfuncs(L, json_nullmark_metamethods, 0); + lua_setmetatable(L, -2); + lua_setfield(L, 1, "null"); + // return library module (that's expected on top of stack): return 1; }