Youâre using âpairsâ to iterate with, which will always give them in semi-random order. You need to use âipairsâ or a numerical âforâ loop (âfor i=1,10â, etc.) if you want them in order.
Of course the indices of your table donât start at 1 and are not always consecutive, so âipairsâ wonât work with it, and the numerical âforâ loop would take some wrangling. This seems like the real problem to me. How did you create this table? Why are the indices not 1, 2, 3, 4, etc.?
Random indices for lists of items with random indicesâŚbut you want to iterate through them in orderâŚyou really like to make life difficult for yourself, eh? What are you trying to do with these, exactly?
If you want to keep âpreview_nodesâ as a âmapâ, the way you have it, I suggest you keep track of the maximum index in each list, and iterate using that. In other words: every time you add or remove a âuser_idâ to âpreview_nodesâ, check what the highest âuser_idâ is, and remember that. That would make iterating in order very easy:
for i=1,highest_user_id do
local nodes = preview_nodes[i]
if nodes then
-- do whatever you wanted to do
end
end
Another way, would be to make âpreview_nodesâ a simple list, (i.e. donât use âuser_idâ as the key) and sort it every time you change it, using table.sort.
-- Add new entries like this:
local user_preview = { id = user_id, places = {} }
table.insert(preview_nodes, user_preview)
-- then use table.sort with a custom sorting function.
-- so preview_nodes would look like this:
preview_nodes = {
{ id = 2, places = {...} },
{ id = 3, places = {...} },
{ id = 6, places = {...} }
}
-- instead of like this:
preview_nodes = {
[2] = {...},
[3] = {...},
[6] = {...}
}
So then âipairsâ would work:
for _,user_preview in ipairs(preview_nodes) do
local user_id = user_preview.id
for _,place in ipairs(user_preview.places) do
-- do stuff
end
end
Well, if you want to do more complicated things, then your code gets more complicated. Itâs best to not waste too much time trying to avoid the inevitable.
The first option is pretty darn simple. Just one math.max() when adding, and a little backwards search loop when removing (and only if itâs the last one).