Page 1 of 1

Looping through table inception

Posted: Mon May 06, 2019 6:19 am
by BountieHuntre
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

Posted: Mon May 06, 2019 11:40 am
by veethree
What you need is recursion.

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
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.

Re: Looping through table inception

Posted: Thu May 09, 2019 6:24 am
by HDPLocust
Every ui element can contain list of child elements:

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
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:getAllParents()
  local parentlist = {}
  
  local parent = self.parent
  while parent do
    table.insert(parentlist, parent)
    parent = parent.parent
  end
  
  return parentlist
end