Table help! How to rearrange the orders of indexes in a table?

I know that there are other answers out there for this, but none like the way I have it.

for i,v in pairs(Waypoints) do	
	if (i%2 == 1) then
		Waypoints[i] = nil
	else
		i = i/2 --- The part I need help with the most.
	end
end

Basically, what I’ll explain what this does, and then I need help with after.

So, this table is basically composed of multiple tables. Each table inside the main table has a value of a position that separates it 4 studs away from all other mini-tables. I wanted to increase this to 8 studs away from each other. Therefore, it got rid of half of the indexes by getting rid of all odd numbers.

Now, the problem is the indexes are now not in order. They were originally listed as:

local table = {1,2,3,4,5,6,7,8,9,10} --- Not used in the code, just used as a example.

Now, after that action takes place. They’re now listed as:

local table = {2,4,6,8,10} --- Not used in the code, just used as a example.

My question is how do I sort them all back in a numerical order. I am not the most experienced with tables, so I don’t know how to resort all of them, or divide their index number by half.

The goal is to have the table laid out like this:

local table = {1,2,3,4,5} --- Not used in the code, just used as a example.

How, do I go about that?

You can do table.sort(table)

Right, but I’m not sure how to go about it.

I didnt get it but can you tell what you are wanting to do with this code? It sounded pretty confusing

Changing the order of the mini-tables within the main table. They are all even numbers right now, but I want them to be in a regular numerical order.

1 Like

So for this you could try using a copy of the table and changing that copy to even numbers or back to normal numbers.

Something like:

local ogTbl = {1, 2, 3, 4, 5, 6, 7}
local copyTbl = {1, 2, 3, 4, 5, 6, 7}

for i,v in pairs(copyTbl) do
      if (i%2 == 1) then
            copyTbl[i] = nil
      else
          copyTbl[i*0.5] = v
          copyTbl[i] = nil
      end
end

Basically, what this does is:

1,2,3,4,5,6,7

Removes the 1st index, adds a new 1st index with the value of the 2nd index and then deletes the 2nd index value.

Soo:
1 = nil
2*0.5 = value of 2
2 = nil
3 = nil
4*0.5 = value of 4
4 = nil
Then goes ahead…

3 Likes