Issue with tables/loops

Hi.

I’m working on an AI system, that works by nodes - going back and forth between their nodes. This relies on the nodes being named A-Z in studio to set the order of them, but, when handling the nodes in a for-loop such as this:

for i,v in pairs(nodelist:GetChildren()) do
table.insert(nodetable, v)
end

The nodes are being printed out in this order:
image
This is causing major issues with the system - I’m not sure why it’s doing this.

You should try using

ipairs()

instead of pairs(), as ipairs iterates over the array in numerical order(not random)

1 Like

I never knew this, thank you, is there any difference between ipairs and pairs, aside from the aforementioned

ipairs can only iterate over lists of items, meaning tables with integer keys. pairs is used to iterate over dictionaries such as this

local dict = {
    entryA = "test",
    entryB = "apple"
}

Can ipairs iterate over actual objects, with :GetChildren()

Turns out this is not what I was looking for

ipairs sorts it via integers, I’m using pairs, which goes over it in order (or is meant to) but it still not working the way I’m hoping

I’m not sure what’s occuring causing these to be messed up, but ipairs is not the solution, the nodes should be sorted through in A, B, C, D order as that is how they are set in workspace

Have you tried table.sort?

local children = nodelist:GetChildren()

table.sort(children, function(a, b)
   return a.Name:byte(#a.Name) < b.Name:byte(#b.Name)
end)
1 Like

Oh yeah I missed that. GetChildren doesn’t get the objects in order. I think it might depend on when they load in. This is probably the answer you’re looking for.

local nodes = nodelist:GetChildren()
table.sort(nodes, function(l, r) return l.Name < r.Name end)
for _, node in ipairs(nodes) do
	print(node.Name) --NodeA, NodeB, NodeC, NodeD
end