From c0516ac151bc42a3547751775412d154586e9f89 Mon Sep 17 00:00:00 2001 From: Sainan Date: Sun, 26 Jan 2025 06:49:54 +0100 Subject: [PATCH] Add table.values --- src/ltablib.cpp | 36 +++++++++++++++++++++++++++++------- testes/pluto/basic.pluto | 5 +++++ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/src/ltablib.cpp b/src/ltablib.cpp index acc6028d0..9980cfc10 100644 --- a/src/ltablib.cpp +++ b/src/ltablib.cpp @@ -803,19 +803,40 @@ static int tkeys (lua_State *L) { lua_newtable(L); lua_Integer i = 0; lua_pushnil(L); - /* stack now: tKeys, key */ + /* stack now: res, key */ while (lua_next(L, 1)) { - /* stack now: tKeys, key, value */ + /* stack now: res, key, value */ lua_pop(L, 1); - /* stack now: tKeys, key */ + /* stack now: res, key */ lua_pushinteger(L, ++i); - /* stack now: tKeys, key, index */ + /* stack now: res, key, index */ lua_pushvalue(L, -2); - /* stack now: tKeys, key, index, key */ + /* stack now: res, key, index, key */ lua_settable(L, -4); - /* stack now: tKeys, key */ + /* stack now: res, key */ + } + /* stack now: res */ + return 1; +} + + +static int tvalues (lua_State *L) { + lua_newtable(L); + lua_Integer i = 0; + lua_pushnil(L); + /* stack now: res, key */ + while (lua_next(L, 1)) { + /* stack now: res, key, value */ + lua_pushinteger(L, ++i); + /* stack now: res, key, value, index */ + lua_pushvalue(L, -2); + /* stack now: res, key, value, index, value */ + lua_settable(L, -5); + /* stack now: res, key, value */ + lua_pop(L, 1); + /* stack now: res, key */ } - /* stack now: tKeys */ + /* stack now: res */ return 1; } @@ -1005,6 +1026,7 @@ static const luaL_Reg tab_funcs[] = { {"deduped", tdeduplicate}, {"deduplicated", tdeduplicated}, {"keys", tkeys}, + {"values", tvalues}, {"modget", modget}, {"modset", modset}, {"back", tback}, diff --git a/testes/pluto/basic.pluto b/testes/pluto/basic.pluto index b998f4021..1425c2bd4 100644 --- a/testes/pluto/basic.pluto +++ b/testes/pluto/basic.pluto @@ -2044,6 +2044,11 @@ do assert(keys:contains("b")) assert(keys:contains("c")) end +do + local t = { a = 1, b = 2, c = 3 } + assert(#t == 0) + assert(#t:values() == 3) +end do local test_table_1 = {1, 2, 2, 3, 1} local counts_1 = test_table_1:countvalues()