Add table.deep_foreach_any

master
Lars Mueller 2021-07-03 12:19:44 +02:00
parent 7a82efb75f
commit 95415c0929
2 changed files with 34 additions and 0 deletions

View File

@ -321,6 +321,22 @@ function foreach(table, func)
end
end
function deep_foreach_any(table, func)
local seen = {}
local function visit(value)
func(value)
if type(value) == "table" then
if seen[value] then return end
seen[value] = true
for k, v in pairs(value) do
visit(k)
visit(v)
end
end
end
visit(table)
end
function foreach_value(table, func)
for _, v in pairs(table) do
func(v)

View File

@ -61,6 +61,24 @@ do
rope:write" "
rope:write"world"
assert(rope:to_text() == "hello world", rope:to_text())
tab = {a = 1, b = {2}}
tab[3] = tab
local contents = {
a = 1,
[1] = 1,
b = 1,
[tab.b] = 1,
[2] = 1,
[tab] = 1,
[3] = 1
}
table.deep_foreach_any(tab, function(content)
assert(contents[content], content)
contents[content] = 2
end)
for _, value in pairs(contents) do
assert(value == 2)
end
end
-- heap