Running table values numerically

when I use [Lua]PrintTable(Placetable)[/Lua] it works perfectly and prints this
[Lua]
918 = Bot49
1000826 = SweeneyPaul
2912 = Bot43
555 = Bot48
1001874 = Bot46
498 = Bot44
2289 = Bot47
853 = Bot45
[/Lua]
but im trying to order these values in ascending order so I used
[Lua]
function TestTable()
for k,v in ipairs(Placetable) do
print(v)
end
end
concommand.Add(“TT”,TestTable)
[/Lua]
but in console in just dosent print anything
what am I doing wrong?

ipairs is meant for tables with numerical indices starting from 1. For other indices like your table, I’d use this.

[lua]local idxTbl = {}
for k,v in pairs( Placetable ) do
idxTbl[#idxTbl + 1] = k
end
table.sort(idxTbl)

for k,v in ipairs( idxTbl ) do
print( k, Placetable[v] )
end[/lua]

thanks mate works perfectly but just one thing I was wodering, why use table.sort if you use ipairs?

This is your initial table. (Placetable in the above code)


918 =   Bot49
1000826 =   SweeneyPaul
2912    =   Bot43
555 =   Bot48
1001874 =   Bot46
498 =   Bot44
2289    =   Bot47
853 =   Bot45

You can’t iterate through it using ipairs because ipairs starts from 1 and goes up until it finds a nil value. Here, Placetable[1] == nil, so nothing is printed.

The first bit of code before table.sort(idxTbl) creates a table called idxTbl which contains the indices of Placetable in a completely arbitrary order, since it’s using pairs. For instance, you might get this:


1 = 1000826
2 = 498
3 = 853
4 = 2289
5 = 918
6 = 555
7 = 1001874
8 = 2912

Now you have a table which is usable with ipairs, but since you want to sort it in ascending order, you need to use table.sort, which will give you this:


1 = 498
2 = 555
3 = 853
4 = 918
5 = 2289
6 = 2912
7 = 1000826
8 = 1001874

You get a neat sorted table of indices through which you can easily iterate using ipairs.