lua-users home
lua-l archive

Re: table.remove problem

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Patrick Donnelly wrote:
> I've found something I believe is undocumented in the manual about the
> behavior of table.remove. If you have a table (as an array) with n
> elements and you call table.remove(t, n+1) or with anything greater
> than n, you remove the last element.
Wow. I hadn't noticed that:
$ /usr/local/bin/lua -e "t={1,2,3} table.remove(t,4) print(#t)"
2
I don't know whether this was the intended behavior, but I don't like
it. I would prefer that it do nothing if the index is invalid.
Here's a one-line patch that checks the index first:
----------------
*** ltablib-orig.c 2007年11月13日 08:00:18.000000000 -0500
--- ltablib.c 2007年11月13日 08:21:15.000000000 -0500
***************
*** 118,124 ****
 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' */
 luaL_setn(L, 1, e - 1); /* t.n = n-1 */
 lua_rawgeti(L, 1, pos); /* result = t[pos] */
 for ( ;pos<e; pos++) {
--- 118,124 ----
 static int tremove (lua_State *L) {
 int e = aux_getn(L, 1);
 int pos = luaL_optint(L, 2, e);
! if ((pos > e) || (pos <= 0)) return 0; /* check index and size */
 luaL_setn(L, 1, e - 1); /* t.n = n-1 */
 lua_rawgeti(L, 1, pos); /* result = t[pos] */
 for ( ;pos<e; pos++) {
----------------
After patch:
$ ./lua -e "t={1,2,3} table.remove(t,4) print(#t)"
3
Doug
-- 
Innovative Concepts, Inc. www.innocon.com 703-893-2007 x220

AltStyle によって変換されたページ (->オリジナル) /