diff --git a/ltablib.c b/ltablib.c index 9d123605..a8214d29 100644 --- a/ltablib.c +++ b/ltablib.c @@ -1,5 +1,5 @@ /* -** $Id: ltablib.c,v 1.34 2005/08/15 14:12:32 roberto Exp roberto $ +** $Id: ltablib.c,v 1.35 2005/08/26 17:36:32 roberto Exp roberto $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ @@ -40,9 +40,7 @@ static int foreach (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checktype(L, 2, LUA_TFUNCTION); lua_pushnil(L); /* first key */ - for (;;) { - if (lua_next(L, 1) == 0) - return 0; + while (lua_next(L, 1)) { lua_pushvalue(L, 2); /* function */ lua_pushvalue(L, -3); /* key */ lua_pushvalue(L, -3); /* value */ @@ -51,6 +49,23 @@ static int foreach (lua_State *L) { return 1; lua_pop(L, 2); /* remove value and result */ } + return 0; +} + + +static int maxn (lua_State *L) { + lua_Number max = 0; + luaL_checktype(L, 1, LUA_TTABLE); + lua_pushnil(L); /* first key */ + while (lua_next(L, 1)) { + lua_pop(L, 1); /* remove value */ + if (lua_type(L, -1) == LUA_TNUMBER) { + lua_Number v = lua_tonumber(L, -1); + if (v > max) max = v; + } + } + lua_pushnumber(L, max); + return 1; } @@ -241,6 +256,7 @@ static const luaL_Reg tab_funcs[] = { {"foreach", foreach}, {"foreachi", foreachi}, {"getn", getn}, + {"maxn", maxn}, {"insert", tinsert}, {"remove", tremove}, {"setn", setn},