webmcp

changeset 157:004d2d50419e

Allow direct usage of json.null values in JSON library (for writing, not reading)
author jbe
date Thu Jul 31 03:45:33 2014 +0200 (2014-07-31)
parents 88b613f5bc22
children d42a7a840358
files libraries/json/json.c
line diff
     1.1 --- a/libraries/json/json.c	Thu Jul 31 03:19:09 2014 +0200
     1.2 +++ b/libraries/json/json.c	Thu Jul 31 03:45:33 2014 +0200
     1.3 @@ -36,6 +36,12 @@
     1.4    JSON_REGENT arraymt;    // metatable for JSON arrays
     1.5  } json_registry;
     1.6  
     1.7 +// returns the string "<JSON null marker>":
     1.8 +static int json_nullmark_tostring(lua_State *L) {
     1.9 +  lua_pushliteral(L, "<JSON null marker>");
    1.10 +  return 1;
    1.11 +}
    1.12 +
    1.13  // marks a Lua table as JSON object or JSON array:
    1.14  // (returns its modified argument or a new table if argument is nil)
    1.15  static int json_mark(lua_State *L, JSON_REGPOINTER mt) {
    1.16 @@ -739,6 +745,10 @@
    1.17    int needsep = 0;
    1.18    lua_Integer idx;
    1.19    lua_settop(L, 1);
    1.20 +  if (json_isnullmark(L, 1)) {
    1.21 +    lua_pushnil(L);
    1.22 +    lua_replace(L, 1);
    1.23 +  }
    1.24    switch (lua_type(L, 1)) {
    1.25    case LUA_TNIL:
    1.26      lua_pushliteral(L, "null");
    1.27 @@ -889,6 +899,12 @@
    1.28    {NULL, NULL}
    1.29  };
    1.30  
    1.31 +// metamethods for JSON null marker:
    1.32 +static const struct luaL_Reg json_nullmark_metamethods[] = {
    1.33 +  {"__tostring", json_nullmark_tostring},
    1.34 +  {NULL, NULL}
    1.35 +};
    1.36 +
    1.37  // initializes json library:
    1.38  int luaopen_json(lua_State *L) {
    1.39    // empty stack:
    1.40 @@ -918,7 +934,12 @@
    1.41    lua_rawset(L, -3);
    1.42    lua_setmetatable(L, -2);
    1.43    json_regstore(L, shadowtbl);
    1.44 -  // return library module stored on lowest stack position:
    1.45 -  lua_settop(L, 1);
    1.46 +  // set metatable of null marker and make it available through library module:
    1.47 +  json_pushnullmark(L);
    1.48 +  lua_newtable(L);
    1.49 +  luaL_setfuncs(L, json_nullmark_metamethods, 0);
    1.50 +  lua_setmetatable(L, -2);
    1.51 +  lua_setfield(L, 1, "null");
    1.52 +  // return library module (that's expected on top of stack):
    1.53    return 1;
    1.54  }

Impressum / About Us