Skip to content

Instantly share code, notes, and snippets.

@dri-richard
Created August 13, 2023 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dri-richard/7b6039ba419f8ca0d41d60f1c7e6f137 to your computer and use it in GitHub Desktop.
Save dri-richard/7b6039ba419f8ca0d41d60f1c7e6f137 to your computer and use it in GitHub Desktop.
Get a full gui node hierarchy from a specified root id in the Defold engine
function build_hierarchy(root)
local node_and_descendants = {}
local node_info = {}
local all_nodes = gui.get_tree(gui.get_node(root))
-- Build an array of (node + its descendants) for each node
for node_id,_ in pairs(all_nodes) do
local nodes
if node_id == root then
nodes = all_nodes -- avoid calling get_tree again for the root node
else
nodes = gui.get_tree(gui.get_node(node_id))
end
local node_ids = {}
for k,v in pairs(nodes) do
table.insert(node_ids, k)
end
node_and_descendants[node_id] = node_ids
end
-- Sort the array so that leaf nodes are first, and the root last
local all_node_ids = node_and_descendants[root]
table.sort(all_node_ids, function(a,b)
return #node_and_descendants[a] < #node_and_descendants[b]
end)
local unparented_children = {}
for _,node_id in ipairs(all_node_ids) do
if #node_and_descendants[node_id] == 1 then
-- leaf node, has no children
node_info[node_id] = {id = node_id, node = all_nodes[node_id]}
else
children = {}
for _,child_id in ipairs(node_and_descendants[node_id]) do
if child_id ~= node_id and unparented_children[child_id] then
children[child_id] = node_info[child_id]
unparented_children[child_id] = nil
end
end
node_info[node_id] = {id = node_id, node = all_nodes[node_id], children = children}
end
unparented_children[node_id] = node_info[node_id]
end
return node_info[root]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment