| 2230 | * converted to a different type. */ |
| 2231 | #define LDB_MAX_VALUES_DEPTH (LUA_MINSTACK/2) |
| 2232 | sds ldbCatStackValueRec(sds s, lua_State *lua, int idx, int level) { |
| 2233 | int t = lua_type(lua,idx); |
| 2234 | |
| 2235 | if (level++ == LDB_MAX_VALUES_DEPTH) |
| 2236 | return sdscat(s,"<max recursion level reached! Nested table?>"); |
| 2237 | |
| 2238 | switch(t) { |
| 2239 | case LUA_TSTRING: |
| 2240 | { |
| 2241 | size_t strl; |
| 2242 | char *strp = (char*)lua_tolstring(lua,idx,&strl); |
| 2243 | s = sdscatrepr(s,strp,strl); |
| 2244 | } |
| 2245 | break; |
| 2246 | case LUA_TBOOLEAN: |
| 2247 | s = sdscat(s,lua_toboolean(lua,idx) ? "true" : "false"); |
| 2248 | break; |
| 2249 | case LUA_TNUMBER: |
| 2250 | s = sdscatprintf(s,"%g",(double)lua_tonumber(lua,idx)); |
| 2251 | break; |
| 2252 | case LUA_TNIL: |
| 2253 | s = sdscatlen(s,"nil",3); |
| 2254 | break; |
| 2255 | case LUA_TTABLE: |
| 2256 | { |
| 2257 | int expected_index = 1; /* First index we expect in an array. */ |
| 2258 | int is_array = 1; /* Will be set to null if check fails. */ |
| 2259 | /* Note: we create two representations at the same time, one |
| 2260 | * assuming the table is an array, one assuming it is not. At the |
| 2261 | * end we know what is true and select the right one. */ |
| 2262 | sds repr1 = sdsempty(); |
| 2263 | sds repr2 = sdsempty(); |
| 2264 | lua_pushnil(lua); /* The first key to start the iteration is nil. */ |
| 2265 | while (lua_next(lua,idx-1)) { |
| 2266 | /* Test if so far the table looks like an array. */ |
| 2267 | if (is_array && |
| 2268 | (lua_type(lua,-2) != LUA_TNUMBER || |
| 2269 | lua_tonumber(lua,-2) != expected_index)) is_array = 0; |
| 2270 | /* Stack now: table, key, value */ |
| 2271 | /* Array repr. */ |
| 2272 | repr1 = ldbCatStackValueRec(repr1,lua,-1,level); |
| 2273 | repr1 = sdscatlen(repr1,"; ",2); |
| 2274 | /* Full repr. */ |
| 2275 | repr2 = sdscatlen(repr2,"[",1); |
| 2276 | repr2 = ldbCatStackValueRec(repr2,lua,-2,level); |
| 2277 | repr2 = sdscatlen(repr2,"]=",2); |
| 2278 | repr2 = ldbCatStackValueRec(repr2,lua,-1,level); |
| 2279 | repr2 = sdscatlen(repr2,"; ",2); |
| 2280 | lua_pop(lua,1); /* Stack: table, key. Ready for next iteration. */ |
| 2281 | expected_index++; |
| 2282 | } |
| 2283 | /* Strip the last " ;" from both the representations. */ |
| 2284 | if (sdslen(repr1)) sdsrange(repr1,0,-3); |
| 2285 | if (sdslen(repr2)) sdsrange(repr2,0,-3); |
| 2286 | /* Select the right one and discard the other. */ |
| 2287 | s = sdscatlen(s,"{",1); |
| 2288 | s = sdscatsds(s,is_array ? repr1 : repr2); |
| 2289 | s = sdscatlen(s,"}",1); |
no test coverage detected