Looping through table inception

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
BountieHuntre
Prole
Posts: 1
Joined: Thu Apr 04, 2019 1:24 am

Looping through table inception

Post 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.
User avatar
veethree
Inner party member
Posts: 877
Joined: Sat Dec 10, 2011 7:18 pm

Re: Looping through table inception

Post 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.
User avatar
HDPLocust
Citizen
Posts: 65
Joined: Thu Feb 19, 2015 10:56 pm
Location: Swamp
Contact:

Re: Looping through table inception

Post 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
Science and violence
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 9 guests