diff --git a/table.lua b/table.lua index ca14fcf..b96f89b 100644 --- a/table.lua +++ b/table.lua @@ -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) diff --git a/test.lua b/test.lua index 1ac2a16..e230c8e 100644 --- a/test.lua +++ b/test.lua @@ -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