Jump to content

Sorting table


Recommended Posts

Help me please with table sorting.

I want to write a custom race event script for play. The idea is clients send their progress like 23/40cp to the server, that adds them into a table, the table gets sorted and then the rankings will shown. Please help me how could i idendify the players and their rank.

the table in server would look like

racers = {somebody = 34,

idk = 12,

racer20 = 20}

then sort racers table and write current ranks.

But you can tell me other variations if you know easier ones.

Link to comment

You can try by bubble sorting.

Let's say you got a table called racers what holds playerVar = checkpointNumber.

So, moving into code:

racers = { 
     somebody = 10, 
     else = 17, 
     pete = 5, 
     randomPlayerVar = 25, 
for i = 1, #racers do 
     for j = #racers, 1, -1 do -- not sure if this line is ok though 
          if racers[i] < racers[j] then 
               local temp = racers[i] 
               racers[i] = racers[j] 
               racers[j] = temp 

Link to comment
Do you think im moron? I tried, it does not work in this case.

It does not, because non-numerical indexed tables don't have an order. However, you can organise your table like this:

local racers = { 
  { player = somePlayer, rank = 20 }, -- "somePlayer" would be a player element 
  { player = anotherPlayer, rank = 5 }, -- "anotherPlayer" would be a player element 
  { player = me, rank = 30 }, -- "me" would be a player element 
  { player = cheater, rank = 140 } } -- "cheater" would be a player element 

You can then sort this table:

table.sort (racers, function (a, b) return a.rank > b.rank end) 

Link to comment
  • 3 weeks later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...