# HG changeset patch # User jbe # Date 1406418705 -7200 # Node ID e3e5bf890aad5ff7389e6915a5f70fb438dbd524 # Parent ece4e6f683c9ded59d0eb2f33dfe6133dac0075d Set json.metatable in JSON library for any JSON object/array diff -r ece4e6f683c9 -r e3e5bf890aad libraries/json/json.c --- a/libraries/json/json.c Sat Jul 26 23:40:43 2014 +0200 +++ b/libraries/json/json.c Sun Jul 27 01:51:45 2014 +0200 @@ -3,9 +3,9 @@ #include #include -#define JSON_UPVAL_ARYLEN lua_upvalueindex(1) +#define JSON_UPVAL_METATABLE lua_upvalueindex(1) #define JSON_UPVAL_NULLS lua_upvalueindex(2) -#define JSON_UPVAL_METATABLE lua_upvalueindex(3) +#define JSON_UPVAL_ARYLEN lua_upvalueindex(3) #define JSON_STATE_VALUE 0 #define JSON_STATE_OBJECT_KEY 1 @@ -44,7 +44,9 @@ if (mode != JSON_STATE_VALUE && mode != JSON_STATE_OBJECT_VALUE && mode != JSON_STATE_ARRAY_VALUE) goto json_import_syntax_error; pos++; - lua_newtable(L); + lua_newtable(L); // the actual JSON object + lua_pushvalue(L, JSON_UPVAL_METATABLE); + lua_setmetatable(L, -2); lua_newtable(L); // stores set of NULL values lua_pushvalue(L, -2); lua_pushvalue(L, -2); @@ -56,7 +58,9 @@ if (mode != JSON_STATE_VALUE && mode != JSON_STATE_OBJECT_VALUE && mode != JSON_STATE_ARRAY_VALUE) goto json_import_syntax_error; pos++; - lua_newtable(L); + lua_newtable(L); // the actual JSON array + lua_pushvalue(L, JSON_UPVAL_METATABLE); + lua_setmetatable(L, -2); lua_newtable(L); // stores set of NULL values lua_pushvalue(L, -2); lua_pushvalue(L, -2); @@ -242,8 +246,11 @@ int luaopen_json(lua_State *L) { lua_newtable(L); // library table + lua_newtable(L); // metatable for JSON objects and JSON arrays + lua_pushvalue(L, -1); + lua_setfield(L, -3, "metatable"); + lua_newtable(L); // ephemeron table to store a set of keys associated with JSON-null values lua_newtable(L); // ephemeron table to store the length of arrays (that may contain nil's) - lua_newtable(L); // ephemeron table to store a set of keys associated with JSON-null values lua_newtable(L); // meta table for ephemeron table lua_pushliteral(L, "__mode"); lua_pushliteral(L, "k"); @@ -251,6 +258,6 @@ lua_pushvalue(L, -1); lua_setmetatable(L, -3); lua_setmetatable(L, -2); - luaL_setfuncs(L, json_module_functions, 2); + luaL_setfuncs(L, json_module_functions, 3); return 1; }