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