Skip to content

Commit

Permalink
Add table.filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Sainan committed Aug 25, 2023
1 parent 7bec444 commit b6fb6d4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/ltablib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -476,10 +476,48 @@ static int tcontains(lua_State* L) {
}


static int tfilter(lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_TFUNCTION);

lua_newtable(L);
lua_Integer idx = 1;
lua_pushvalue(L, 1);
lua_pushnil(L);
/* stack now: out, in, key */
while (lua_next(L, -2)) {
/* stack now: out, in, key, value */
lua_pushvalue(L, 2);
lua_pushvalue(L, -2);
/* stack now: out, in, key, value, function, value */
lua_call(L, 1, 1);
/* stack now: out, in, key, value, bKeep */
const bool bKeep = lua_toboolean(L, -1);
lua_pop(L, 1);
/* stack now: out, in, key, value */
if (bKeep) {
lua_pushinteger(L, idx++);
/* stack now: out, in, key, value, idx */
lua_pushvalue(L, -2);
/* stack now: out, in, key, value, idx, value */
lua_settable(L, -6);
/* stack now: out, in, key, value */
}
lua_pop(L, 1);
/* stack now: out, in, key */
}
/* stack now: out, in */
lua_pop(L, 1);
/* stack now: out */
return 1;
}


/* }====================================================== */


static const luaL_Reg tab_funcs[] = {
{"filter", tfilter},
{"foreach", foreach},
{"contains", tcontains},
#ifndef PLUTO_DISABLE_TABLE_FREEZING
Expand Down
7 changes: 7 additions & 0 deletions tests/basic.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,13 @@ do
assert(string.lower("HELLO", -2) == "HELlO")
assert(string.lower("HELLO", -14) == "HELLO")
end
do
local t = { 5, 4, 3, 2, 1 }
t = table.filter(t, |x| -> x % 2 ~= 0)
assert(t[1] == 5)
assert(t[2] == 3)
assert(t[3] == 1)
end

print "Testing default table metatable."
do
Expand Down

0 comments on commit b6fb6d4

Please sign in to comment.