lua

A copy of the Lua development repository
Log | Files | Refs | README

commit f4e762f688935228dd9aa6b2f9e28a5a34f385b1
parent 1ce57628b21433c0cf7e418b0359766e241106ce
Author: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date:   Wed,  6 Feb 2013 16:28:38 -0200

better error checking for 'table.insert' and 'table.remove'

Diffstat:
Mltablib.c | 22++++++++++++----------
1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/ltablib.c b/ltablib.c @@ -1,5 +1,5 @@ /* -** $Id: ltablib.c,v 1.62 2011/09/30 12:45:45 roberto Exp roberto $ +** $Id: ltablib.c,v 1.63 2011/11/28 17:26:30 roberto Exp roberto $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ @@ -16,8 +16,8 @@ #include "lualib.h" -#define aux_getn(L,n) \ - (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n)) +#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n)) + #if defined(LUA_COMPAT_MAXN) @@ -49,7 +49,7 @@ static int tinsert (lua_State *L) { case 3: { int i; pos = luaL_checkint(L, 2); /* 2nd argument is the position */ - if (pos > e) e = pos; /* `grow' array if necessary */ + luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); for (i = e; i > pos; i--) { /* move up elements */ lua_rawgeti(L, 1, i-1); lua_rawseti(L, 1, i); /* t[i] = t[i-1] */ @@ -66,17 +66,19 @@ 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 (!(1 <= pos && pos <= e)) /* position is outside bounds? */ - return 0; /* nothing to remove */ + int size = aux_getn(L, 1); + int pos = luaL_optint(L, 2, size); + if (pos != size) /* validate 'pos' if given */ + luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); + else if (size == 0) /* empty table? */ + return 0; /* return nothing (nil) */ lua_rawgeti(L, 1, pos); /* result = t[pos] */ - for ( ;pos<e; pos++) { + for ( ; pos < size; pos++) { lua_rawgeti(L, 1, pos+1); lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */ } lua_pushnil(L); - lua_rawseti(L, 1, e); /* t[e] = nil */ + lua_rawseti(L, 1, pos); /* t[pos] = nil */ return 1; }