浏览代码

BUG: table.remove removes last element of a table when given
an out-of-bound index

Roberto Ierusalimschy 17 年之前
父节点
当前提交
9f0d62ad9f
共有 2 个文件被更改,包括 28 次插入2 次删除
  1. 25 0
      bugs
  2. 3 2
      ltablib.c

+ 25 - 0
bugs

@@ -1569,6 +1569,31 @@ lstrlib.c:
 ]],
 }
 
+Bug{
+what = [[table.remove removes last element of a table when given
+an out-of-bound index]],
+report = [[Patrick Donnelly, on 11/2007]],
+since = [[at least 5.0]],
+example = [[
+a = {1,2,3}
+table.remove(a, 4)
+print(a[3])   --> nil   (should be 3)
+]],
+patch = [[
+ltablib.c:
+@@ -118,7 +118,8 @@
+ static int tremove (lua_State *L) {
+   int e = aux_getn(L, 1);
+   int pos = luaL_optint(L, 2, e);
+-  if (e == 0) return 0;  /* table is `empty' */
++  if (!(1 <= pos && pos <= e))  /* position is outside bounds? */
++   return 0;  /* nothing to remove */
+   luaL_setn(L, 1, e - 1);  /* t.n = n-1 */
+   lua_rawgeti(L, 1, pos);  /* result = t[pos] */
+   for ( ;pos<e; pos++) {
+]],
+}
+
 Bug{
 what = [[ ]],
 report = [[ , on ]],

+ 3 - 2
ltablib.c

@@ -1,5 +1,5 @@
 /*
-** $Id: ltablib.c,v 1.40 2007/06/21 13:50:53 roberto Exp roberto $
+** $Id: ltablib.c,v 1.41 2007/09/12 20:53:24 roberto Exp roberto $
 ** Library for Table Manipulation
 ** See Copyright Notice in lua.h
 */
@@ -110,7 +110,8 @@ static int tinsert (lua_State *L) {
 static int tremove (lua_State *L) {
   int e = aux_getn(L, 1);
   int pos = luaL_optint(L, 2, e);
-  if (e == 0) return 0;  /* table is `empty' */
+  if (!(1 <= pos && pos <= e))  /* position is outside bounds? */
+    return 0;  /* nothing to remove */
   lua_rawgeti(L, 1, pos);  /* result = t[pos] */
   for ( ;pos<e; pos++) {
     lua_rawgeti(L, 1, pos+1);