mirror of https://github.com/rusefi/lua.git
better error checking for 'table.insert' and 'table.remove'
This commit is contained in:
parent
1ce57628b2
commit
f4e762f688
22
ltablib.c
22
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;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue