From a61d7840ba2d79df8cb73d8c864a99d0eb06d580 Mon Sep 17 00:00:00 2001 From: Thibault Charbonnier Date: Fri, 16 Dec 2016 18:27:49 -0800 Subject: bugfix: preserve 'empty_array_mt' behavior upon multiple loadings of the module. Prior to this fix, when the module would be loaded several times (by-passing `package.loaded`), the `lua_cjson_new` function would override the `empty_array_mt` table in the registry with a new one. Comparison for equality between those tables would then fail, and the behavior would be broken. This was discovered after loading `cjson` *and* `cjson.safe` in the same application, resulting in two calls to `lua_cjson_new`. Signed-off-by: Yichun Zhang (agentzh) --- lua_cjson.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'lua_cjson.c') diff --git a/lua_cjson.c b/lua_cjson.c index 3a77644..1695979 100644 --- a/lua_cjson.c +++ b/lua_cjson.c @@ -1401,10 +1401,21 @@ static int lua_cjson_new(lua_State *l) /* Initialise number conversions */ fpconv_init(); - /* Create empty array metatable */ + /* Test if empty array metatable is in registry */ lua_pushlightuserdata(l, &json_empty_array); - lua_newtable(l); - lua_rawset(l, LUA_REGISTRYINDEX); + lua_rawget(l, LUA_REGISTRYINDEX); + if (lua_isnil(l, -1)) { + /* Create empty array metatable. + * + * If multiple calls to lua_cjson_new() are made, + * this prevents overriding the table at the given + * registry's index with a new one. + */ + lua_pop(l, 1); + lua_pushlightuserdata(l, &json_empty_array); + lua_newtable(l); + lua_rawset(l, LUA_REGISTRYINDEX); + } /* cjson module table */ lua_newtable(l); -- cgit v1.2.3-55-g6feb