Skip to main content

remove

Function remove 

Source
pub fn remove(state: &mut LuaState) -> Result<usize, LuaError>
Expand description

table.remove(t, [pos]). Removes and returns t[pos] (default: the last element, #t), shifting the tail down to close the gap.

The out-of-bounds handling is gated three ways across versions, each pinned against its reference binary by v_remove_out_of_bounds_arg_gate_crossversion:

  • 5.1 (legacy ltablib.c): there is NO luaL_argcheck. An out-of-range pos (outside [1, size]) silently removes nothing and returns ZERO results — never an error.
  • 5.2 / 5.3: luaL_argcheck((lua_Unsigned)pos - 1u <= size, 1, ...) — the offending argument is reported as #1.
  • 5.4 / 5.5: the identical check, but the argument index is #2.
// 5.4.7
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)
    luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 2,
                     "position out of bounds");
  lua_geti(L, 1, pos);
  for ( ; pos < size; pos++) {
    lua_geti(L, 1, pos + 1);
    lua_seti(L, 1, pos);
  }
  lua_pushnil(L);
  lua_seti(L, 1, pos);
  return 1;
}
// 5.1.5
static int tremove (lua_State *L) {
  int e = aux_getn(L, 1);
  int pos = luaL_optint(L, 2, e);
  if (!(1 <= pos && pos <= e)) return 0;  // nothing to remove
  ...
}