diff --git a/ltablib.c b/ltablib.c new file mode 100644 index 00000000..292a8f7a --- /dev/null +++ b/ltablib.c @@ -0,0 +1,308 @@ +/* +** $Id: $ +** Library for Table Manipulation +** See Copyright Notice in lua.h +*/ + + +#include + +#include "lua.h" + +#include "lauxlib.h" +#include "luadebug.h" +#include "lualib.h" + + + + +static int luaB_foreachi (lua_State *L) { + int n, i; + luaL_check_type(L, 1, LUA_TTABLE); + luaL_check_type(L, 2, LUA_TFUNCTION); + n = lua_getn(L, 1); + for (i=1; i<=n; i++) { + lua_pushvalue(L, 2); /* function */ + lua_pushnumber(L, i); /* 1st argument */ + lua_rawgeti(L, 1, i); /* 2nd argument */ + lua_rawcall(L, 2, 1); + if (!lua_isnil(L, -1)) + return 1; + lua_pop(L, 1); /* remove nil result */ + } + return 0; +} + + +static int luaB_foreach (lua_State *L) { + luaL_check_type(L, 1, LUA_TTABLE); + luaL_check_type(L, 2, LUA_TFUNCTION); + lua_pushnil(L); /* first key */ + for (;;) { + if (lua_next(L, 1) == 0) + return 0; + lua_pushvalue(L, 2); /* function */ + lua_pushvalue(L, -3); /* key */ + lua_pushvalue(L, -3); /* value */ + lua_rawcall(L, 2, 1); + if (!lua_isnil(L, -1)) + return 1; + lua_pop(L, 2); /* remove value and result */ + } +} + + +static void aux_setn (lua_State *L, int t, int n) { + lua_pushliteral(L, "n"); + lua_pushnumber(L, n); + lua_rawset(L, t); +} + + +static int luaB_getn (lua_State *L) { + luaL_check_type(L, 1, LUA_TTABLE); + lua_pushnumber(L, lua_getn(L, 1)); + return 1; +} + + +static int luaB_tinsert (lua_State *L) { + int v = lua_gettop(L); /* number of arguments */ + int n, pos; + luaL_check_type(L, 1, LUA_TTABLE); + n = lua_getn(L, 1); + if (v == 2) /* called with only 2 arguments */ + pos = n+1; + else { + v = 3; /* function may be called with more than 3 args */ + pos = luaL_check_int(L, 2); /* 2nd argument is the position */ + } + if (pos > n+1) n = pos-1; + aux_setn(L, 1, n+1); /* t.n = n+1 */ + for (; n>=pos; n--) { + lua_rawgeti(L, 1, n); + lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */ + } + lua_pushvalue(L, v); + lua_rawseti(L, 1, pos); /* t[pos] = v */ + return 0; +} + + +static int luaB_tremove (lua_State *L) { + int pos, n; + luaL_check_type(L, 1, LUA_TTABLE); + n = lua_getn(L, 1); + pos = luaL_opt_int(L, 2, n); + if (n <= 0) return 0; /* table is `empty' */ + aux_setn(L, 1, n-1); /* t.n = n-1 */ + lua_rawgeti(L, 1, pos); /* result = t[pos] */ + for ( ;pos= P */ + while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) { + if (i>u) lua_error(L, "invalid order function for sorting"); + lua_pop(L, 1); /* remove a[i] */ + } + /* repeat --j until a[j] <= P */ + while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) { + if (j