mirror of
https://github.com/appgurueu/modlib.git
synced 2024-11-26 09:13:53 +01:00
Add table.deep_foreach_any
This commit is contained in:
parent
7a82efb75f
commit
95415c0929
16
table.lua
16
table.lua
@ -321,6 +321,22 @@ function foreach(table, func)
|
|||||||
end
|
end
|
||||||
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)
|
function foreach_value(table, func)
|
||||||
for _, v in pairs(table) do
|
for _, v in pairs(table) do
|
||||||
func(v)
|
func(v)
|
||||||
|
18
test.lua
18
test.lua
@ -61,6 +61,24 @@ do
|
|||||||
rope:write" "
|
rope:write" "
|
||||||
rope:write"world"
|
rope:write"world"
|
||||||
assert(rope:to_text() == "hello world", rope:to_text())
|
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
|
end
|
||||||
|
|
||||||
-- heap
|
-- heap
|
||||||
|
Loading…
Reference in New Issue
Block a user