Looping through table inception
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
-
- Prole
- Posts: 1
- Joined: Thu Apr 04, 2019 1:24 am
Looping through table inception
This post is not necessarily about an arrow, however a question on how to loop through a table that has a table that has a table and so on. I'm trying to make a "ui" where you can assign parents to elements. An element's children are placed into a table the element has and those children also have tables for elements that are children to them. The problem I have encountered with this is that using for loops would require me to type an infinite amount of them to iterate through every table's table. I'm not super skilled with lua yet but I believe I'm decent, so I'm not sure of any way to do this. Any help would be appreciated. Although I don't think its needed, if you need some of my code, please ask for it.
Re: Looping through table inception
What you need is recursion.
Some thing like
Note: That code is completely untested.
That function doesn't do anything other than iterating, So if you want it to do something with the elements in the table you'd do that within the function.
Some thing like
Code: Select all
function iterate(t)
for i,v in ipairs(t) do
if type(v) == "table" then
iterate(v)
end
end
end
That function doesn't do anything other than iterating, So if you want it to do something with the elements in the table you'd do that within the function.
Re: Looping through table inception
Every ui element can contain list of child elements:
So if "v"-elements of items-list has look-like update function, it will "recursivelly" iterate all tree.
Also if you add parent link to every child, we can gain access to all parents, like
Code: Select all
function widget:update(dt)
for i, v in ipairs(self.items) do
if v.update then v:update(dt) end
end
end
Also if you add parent link to every child, we can gain access to all parents, like
Code: Select all
function widget:getAllParents()
local parentlist = {}
local parent = self.parent
while parent do
table.insert(parentlist, parent)
parent = parent.parent
end
return parentlist
end
Science and violence
Who is online
Users browsing this forum: Bing [Bot] and 6 guests