Skip to content

Commit 4473a53

Browse files
Fabrício Puppimattsta
Fabrício Puppi
authored andcommitted
Fixed faulty implementation of table_is_an_array().
1 parent f44f954 commit 4473a53

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@
99

1010
*.o
1111
*.so
12+
13+
build/

lua_cmsgpack.c

+15-12
Original file line numberDiff line numberDiff line change
@@ -372,29 +372,32 @@ static void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
372372
* of keys from numerical keys from 1 up to N, with N being the total number
373373
* of elements, without any hole in the middle. */
374374
static int table_is_an_array(lua_State *L) {
375-
long count = 0, idx = 0;
375+
int count = 0, max = 0;
376376
lua_Number n;
377377

378+
/* Stack top on function entry */
379+
int stacktop;
380+
381+
stacktop = lua_gettop(L);
382+
378383
lua_pushnil(L);
379384
while(lua_next(L,-2)) {
380385
/* Stack: ... key value */
381386
lua_pop(L,1); /* Stack: ... key */
382-
if (lua_type(L,-1) != LUA_TNUMBER) goto not_array;
383-
n = lua_tonumber(L,-1);
384-
idx = n;
385-
if (idx != n || idx < 1) goto not_array;
387+
if (!lua_isnumber(L,-1) || (n = lua_tonumber(L, -1)) <= 0) {
388+
lua_settop(L, stacktop);
389+
return 0;
390+
}
391+
max = (n > max ? n : max);
386392
count++;
387393
}
388394
/* We have the total number of elements in "count". Also we have
389-
* the max index encountered in "idx". We can't reach this code
395+
* the max index encountered in "max". We can't reach this code
390396
* if there are indexes <= 0. If you also note that there can not be
391-
* repeated keys into a table, you have that if idx==count you are sure
397+
* repeated keys into a table, you have that if max==count you are sure
392398
* that there are all the keys form 1 to count (both included). */
393-
return idx == count;
394-
395-
not_array:
396-
lua_pop(L,1);
397-
return 0;
399+
lua_settop(L, stacktop);
400+
return max == count;
398401
}
399402

400403
/* If the length operator returns non-zero, that is, there is at least

0 commit comments

Comments
 (0)