new function 'table.maxn'

This commit is contained in:
Roberto Ierusalimschy 2005-09-20 14:56:47 -03:00
parent 361a9adba7
commit 0fae476ed4
1 changed files with 20 additions and 4 deletions

View File

@ -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},