aboutsummaryrefslogtreecommitdiff
path: root/ltablib.c
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2005-10-23 15:38:15 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2005-10-23 15:38:15 -0200
commit056b6a8ef480ab72a5705f2e77a3e95f7d8b2218 (patch)
treeeb9960cc494194ccb49895cccdc6f0d41225b1aa /ltablib.c
parent502d8f9a06b85c7a8a0e74a27d6738d92969b9a7 (diff)
downloadlua-056b6a8ef480ab72a5705f2e77a3e95f7d8b2218.tar.gz
lua-056b6a8ef480ab72a5705f2e77a3e95f7d8b2218.tar.bz2
lua-056b6a8ef480ab72a5705f2e77a3e95f7d8b2218.zip
more robust implementation for table.insert
Diffstat (limited to 'ltablib.c')
-rw-r--r--ltablib.c29
1 files changed, 18 insertions, 11 deletions
diff --git a/ltablib.c b/ltablib.c
index b8682b30..c2323eb2 100644
--- a/ltablib.c
+++ b/ltablib.c
@@ -1,5 +1,5 @@
1/* 1/*
2** $Id: ltablib.c,v 1.36 2005/09/20 17:56:47 roberto Exp roberto $ 2** $Id: ltablib.c,v 1.37 2005/10/21 13:47:42 roberto Exp roberto $
3** Library for Table Manipulation 3** Library for Table Manipulation
4** See Copyright Notice in lua.h 4** See Copyright Notice in lua.h
5*/ 5*/
@@ -90,16 +90,23 @@ static int setn (lua_State *L) {
90static int tinsert (lua_State *L) { 90static int tinsert (lua_State *L) {
91 int e = aux_getn(L, 1) + 1; /* first empty element */ 91 int e = aux_getn(L, 1) + 1; /* first empty element */
92 int pos; /* where to insert new element */ 92 int pos; /* where to insert new element */
93 if (lua_isnone(L, 3)) /* called with only 2 arguments */ 93 switch (lua_gettop(L)) {
94 pos = e; /* insert new element at the end */ 94 case 2: { /* called with only 2 arguments */
95 else { 95 pos = e; /* insert new element at the end */
96 int i; 96 break;
97 pos = luaL_checkint(L, 2); /* 2nd argument is the position */ 97 }
98 if (pos > e) e = pos; /* `grow' array if necessary */ 98 case 3: {
99 lua_settop(L, 3); /* function may be called with more than 3 args */ 99 int i;
100 for (i = e; i > pos; i--) { /* move up elements */ 100 pos = luaL_checkint(L, 2); /* 2nd argument is the position */
101 lua_rawgeti(L, 1, i-1); 101 if (pos > e) e = pos; /* `grow' array if necessary */
102 lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ 102 for (i = e; i > pos; i--) { /* move up elements */
103 lua_rawgeti(L, 1, i-1);
104 lua_rawseti(L, 1, i); /* t[i] = t[i-1] */
105 }
106 break;
107 }
108 default: {
109 return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
103 } 110 }
104 } 111 }
105 luaL_setn(L, 1, e); /* new size */ 112 luaL_setn(L, 1, e); /* new size */