lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 1 March 2011 22:49, Tony Finch <dot@dotat.at> wrote:
> Lua works much more consistently when nil is treated the same as the
> absence of a value.
>
> table.insert() should have its two-argument form separated out into a
> table.append() function - which could quite nicely append multiple values.
>
> Tony.
> --
> f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
> Fisher: Variable 3 or 4, becoming southwesterly 4 or 5 in north. Mainly
> slight. Fair. Moderate or good.
>
>
> diff --git a/src/ltablib.c b/src/ltablib.c
> index faabfe5..a425b39 100644
> --- a/src/ltablib.c
> +++ b/src/ltablib.c
> @@ -45,27 +45,25 @@ static int maxn (lua_State *L) {
>  #endif
>
>
> +static int tappend (lua_State *L) {
> +  int n = aux_getn(L, 1);  /* length of array */
> +  int i = n + lua_gettop(L) - 1;  /* plus number of args excluding array */
> +  while (i > n)
> +    lua_rawseti(L, 1, i--);  /* t[i] = v */
> +  return 0;
> +}
> +
> +
>  static int tinsert (lua_State *L) {
>   int e = aux_getn(L, 1) + 1;  /* first empty element */
> -  int pos;  /* where to insert new element */
> -  switch (lua_gettop(L)) {
> -    case 2: {  /* called with only 2 arguments */
> -      pos = e;  /* insert new element at the end */
> -      break;
> -    }
> -    case 3: {
> -      int i;
> -      pos = luaL_checkint(L, 2);  /* 2nd argument is the position */
> -      if (pos > e) e = pos;  /* `grow' array if necessary */
> -      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] */
> -      }
> -      break;
> -    }
> -    default: {
> -      return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
> -    }
> +  int i;
> +  int pos = luaL_checkint(L, 2);  /* where to insert new element */
> +  if (lua_gettop(L) != 3)
> +    return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
> +  if (e < pos) e = pos;  /* `grow' array if necessary */
> +  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] */
>   }
>   lua_rawseti(L, 1, pos);  /* t[pos] = v */
>   return 0;
> @@ -264,6 +262,7 @@ static int sort (lua_State *L) {
>
>
>  static const luaL_Reg tab_funcs[] = {
> +  {"append", tappend},
>   {"concat", tconcat},
>   {"foreach", deprecatedfunc},
>   {"foreachi", deprecatedfunc},

Agreed; this is the most sensible/basic fix for the case of table.insert
Though I might even suggest the elimination of table.append entirely;
it's so trivial to create:
tblappend = function ( t , v ) t [ #t + 1 ] = v ; return v end

Daurn.