|
table.remove (list [, pos])
Removes from list
the element at position pos
, returning the value of the removed element. When pos
is an integer between 1 and #list
, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list]
and erases element list[#list]
; The index pos
can also be 0 when #list
is 0, or #list + 1
; in those cases, the function erases the element list[pos]
.
The default value for pos
is #list
, so that a call table.remove(l)
removes the last element of list l
.
here is a sample:--==================================================== t = {1}table.remove(t,2) --no error, return niltable.remove(t,3) --throw an error: "position out of bounds"--====================================================
"table.remove" is implemented by "tremove" in C, and here is the code about "tremove" in lua5.3:
/*===================================================== static int tremove (lua_State*L) {
lua_Integer size = aux_getn(L, 1, TAB_RW);
lua_Integer pos = luaL_optinteger(L, 2, size);
if (pos != size) /*validate 'pos' if given */
luaL_argcheck(L, 1 <= pos&& pos <= size + 1, 1, " position out of bounds");
lua_geti(L, 1, pos); /*result = t[pos] */
for ( ; pos < size; pos++) {
lua_geti(L, 1, pos + 1);
lua_seti(L, 1, pos); /*t[pos] = t[pos + 1] */
}
lua_pushnil(L);
lua_seti(L, 1, pos); /* t[pos] = nil */
return 1;
}/*=====================================================
I am curious about that why "size + 1" is the validate position? Does the positon length+1 has a special meaning?
thanks everybody!