diff options
| -rw-r--r-- | ltablib.c | 24 |
1 files changed, 20 insertions, 4 deletions
| @@ -1,5 +1,5 @@ | |||
| 1 | /* | 1 | /* |
| 2 | ** $Id: ltablib.c,v 1.34 2005/08/15 14:12:32 roberto Exp roberto $ | 2 | ** $Id: ltablib.c,v 1.35 2005/08/26 17:36:32 roberto Exp roberto $ |
| 3 | ** Library for Table Manipulation | 3 | ** Library for Table Manipulation |
| 4 | ** See Copyright Notice in lua.h | 4 | ** See Copyright Notice in lua.h |
| 5 | */ | 5 | */ |
| @@ -40,9 +40,7 @@ static int foreach (lua_State *L) { | |||
| 40 | luaL_checktype(L, 1, LUA_TTABLE); | 40 | luaL_checktype(L, 1, LUA_TTABLE); |
| 41 | luaL_checktype(L, 2, LUA_TFUNCTION); | 41 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 42 | lua_pushnil(L); /* first key */ | 42 | lua_pushnil(L); /* first key */ |
| 43 | for (;;) { | 43 | while (lua_next(L, 1)) { |
| 44 | if (lua_next(L, 1) == 0) | ||
| 45 | return 0; | ||
| 46 | lua_pushvalue(L, 2); /* function */ | 44 | lua_pushvalue(L, 2); /* function */ |
| 47 | lua_pushvalue(L, -3); /* key */ | 45 | lua_pushvalue(L, -3); /* key */ |
| 48 | lua_pushvalue(L, -3); /* value */ | 46 | lua_pushvalue(L, -3); /* value */ |
| @@ -51,6 +49,23 @@ static int foreach (lua_State *L) { | |||
| 51 | return 1; | 49 | return 1; |
| 52 | lua_pop(L, 2); /* remove value and result */ | 50 | lua_pop(L, 2); /* remove value and result */ |
| 53 | } | 51 | } |
| 52 | return 0; | ||
| 53 | } | ||
| 54 | |||
| 55 | |||
| 56 | static int maxn (lua_State *L) { | ||
| 57 | lua_Number max = 0; | ||
| 58 | luaL_checktype(L, 1, LUA_TTABLE); | ||
| 59 | lua_pushnil(L); /* first key */ | ||
| 60 | while (lua_next(L, 1)) { | ||
| 61 | lua_pop(L, 1); /* remove value */ | ||
| 62 | if (lua_type(L, -1) == LUA_TNUMBER) { | ||
| 63 | lua_Number v = lua_tonumber(L, -1); | ||
| 64 | if (v > max) max = v; | ||
| 65 | } | ||
| 66 | } | ||
| 67 | lua_pushnumber(L, max); | ||
| 68 | return 1; | ||
| 54 | } | 69 | } |
| 55 | 70 | ||
| 56 | 71 | ||
| @@ -241,6 +256,7 @@ static const luaL_Reg tab_funcs[] = { | |||
| 241 | {"foreach", foreach}, | 256 | {"foreach", foreach}, |
| 242 | {"foreachi", foreachi}, | 257 | {"foreachi", foreachi}, |
| 243 | {"getn", getn}, | 258 | {"getn", getn}, |
| 259 | {"maxn", maxn}, | ||
| 244 | {"insert", tinsert}, | 260 | {"insert", tinsert}, |
| 245 | {"remove", tremove}, | 261 | {"remove", tremove}, |
| 246 | {"setn", setn}, | 262 | {"setn", setn}, |
