# How to return table in correct order

Hi, how would I make this table return in the order it’s written?

``````return {
[6] = {
"General of the Army"
},

[5] = {
"General",
"Lieutenant General",
"Major General",
},

[4] = {
"Colonel",
"Lieutenant Colonel",
"Major",
"Captain",
},

[3] = {
"First Lieutenant",
"Second Lieutenant",
"Chief Warrant Officer",
"Warrant Officer",
"Sergeant Major",
},

[2] = {
"First Sergeant",
"Master Sergeant",
"Sergeant First Class",
"Staff Sergeant",
},

[1] = {
"Sergeant",
"Corporal",
"Specialist",
"Private First Class",
"Private",
}
}
``````

The table will be in the order it’s written already.

``````local tbl = require(script.ModuleScript)
--// following prints the tables in order from 1-6
for i = 1, 6 do
print(tbl[i])
end
``````

Am I doing something wrong then? I used a for I,v in pairs loop and it didn’t return in the same order.

Instead of using in pairs, use in ipairs to return it in the correct numerical order.

``````local tbl = require(script.ModuleScript)
--// following prints the tables in order from 1-6
for i, v in ipairs(tbl) do
print(v)
end
``````

Aight so it prints in the opposite order because I start it from 6 down to 1, could I reverse this without changing the module script?

To change this, you would have to use a regular for loop.

``````local tbl = require(script.ModuleScript)
--// following prints the tables in order from 6-1
for i = 6, 1, -1 do
print(tbl[i])
end``````

Suppose I’ll settle with what you said above, thanks a lot anyway.

Of course! As a rule of thumb, iterating through tables in lua using loops always goes in order starting from 1 and going forwards. In order to change the order it goes in, you have to use a regular for loop. For loops allow you to change the rate of change of i, and allow you to change the beginning and end indices.

Here’s a tutorial on loops:

1 Like