webmcp
changeset 125:e3e5bf890aad
Set json.metatable in JSON library for any JSON object/array
author | jbe |
---|---|
date | Sun Jul 27 01:51:45 2014 +0200 (2014-07-27) |
parents | ece4e6f683c9 |
children | bccaa05aada7 |
files | libraries/json/json.c |
line diff
1.1 --- a/libraries/json/json.c Sat Jul 26 23:40:43 2014 +0200 1.2 +++ b/libraries/json/json.c Sun Jul 27 01:51:45 2014 +0200 1.3 @@ -3,9 +3,9 @@ 1.4 #include <stdlib.h> 1.5 #include <string.h> 1.6 1.7 -#define JSON_UPVAL_ARYLEN lua_upvalueindex(1) 1.8 +#define JSON_UPVAL_METATABLE lua_upvalueindex(1) 1.9 #define JSON_UPVAL_NULLS lua_upvalueindex(2) 1.10 -#define JSON_UPVAL_METATABLE lua_upvalueindex(3) 1.11 +#define JSON_UPVAL_ARYLEN lua_upvalueindex(3) 1.12 1.13 #define JSON_STATE_VALUE 0 1.14 #define JSON_STATE_OBJECT_KEY 1 1.15 @@ -44,7 +44,9 @@ 1.16 if (mode != JSON_STATE_VALUE && mode != JSON_STATE_OBJECT_VALUE && mode != JSON_STATE_ARRAY_VALUE) 1.17 goto json_import_syntax_error; 1.18 pos++; 1.19 - lua_newtable(L); 1.20 + lua_newtable(L); // the actual JSON object 1.21 + lua_pushvalue(L, JSON_UPVAL_METATABLE); 1.22 + lua_setmetatable(L, -2); 1.23 lua_newtable(L); // stores set of NULL values 1.24 lua_pushvalue(L, -2); 1.25 lua_pushvalue(L, -2); 1.26 @@ -56,7 +58,9 @@ 1.27 if (mode != JSON_STATE_VALUE && mode != JSON_STATE_OBJECT_VALUE && mode != JSON_STATE_ARRAY_VALUE) 1.28 goto json_import_syntax_error; 1.29 pos++; 1.30 - lua_newtable(L); 1.31 + lua_newtable(L); // the actual JSON array 1.32 + lua_pushvalue(L, JSON_UPVAL_METATABLE); 1.33 + lua_setmetatable(L, -2); 1.34 lua_newtable(L); // stores set of NULL values 1.35 lua_pushvalue(L, -2); 1.36 lua_pushvalue(L, -2); 1.37 @@ -242,8 +246,11 @@ 1.38 1.39 int luaopen_json(lua_State *L) { 1.40 lua_newtable(L); // library table 1.41 + lua_newtable(L); // metatable for JSON objects and JSON arrays 1.42 + lua_pushvalue(L, -1); 1.43 + lua_setfield(L, -3, "metatable"); 1.44 + lua_newtable(L); // ephemeron table to store a set of keys associated with JSON-null values 1.45 lua_newtable(L); // ephemeron table to store the length of arrays (that may contain nil's) 1.46 - lua_newtable(L); // ephemeron table to store a set of keys associated with JSON-null values 1.47 lua_newtable(L); // meta table for ephemeron table 1.48 lua_pushliteral(L, "__mode"); 1.49 lua_pushliteral(L, "k"); 1.50 @@ -251,6 +258,6 @@ 1.51 lua_pushvalue(L, -1); 1.52 lua_setmetatable(L, -3); 1.53 lua_setmetatable(L, -2); 1.54 - luaL_setfuncs(L, json_module_functions, 2); 1.55 + luaL_setfuncs(L, json_module_functions, 3); 1.56 return 1; 1.57 }