Jump to content

Ordering a table.


.:HyPeX:.

Recommended Posts

Hey Guys, how could i do a math arrangement?

Lets say i get player table:

  
PTable = {} 
PTable[Player1] 
PTable[Player2] 
PTable[Player3] 
  

Now, each player has an element data. (Or value assigned)

  
PTable = {} 
PTable[Player1] = 50 
PTable[Player2] = 45 
PTable[Player3] = 55 
  

Now, how can i order them in order to be from biggest to smallest?

  
PTable = {} 
PTable[Player3] = 55 
PTable[Player1] = 50 
PTable[Player2] = 45 
  

Thanks

HyPeX

PD: Thought about something with math.max, but idk if there's a shorter way.

Link to comment

Did a quick test:

  
PTable = {} 
PTable["Player1"] = 50 
PTable["Player2"] = 45 
PTable["Player3"] = 55 
  
table.sort(PTable, function(a,b) return aend) 
  
for i,v in pairs(PTable) do 
outputServerLog("Player: "..i.." Value:"  .. v) 
  
end 

It only outputed the table normally...

Link to comment
  
PTable = {} 
table.insert(PTable, 50) 
table.insert(PTable, 45) 
table.insert(PTable, 55) 
  
table.sort(PTable, function(a,b) return aend) 
  
for i,v in ipairs(PTable) do 
outputServerLog("Player: "..i.." Value:"  .. v) 
  
end 

Did it like this and it did sorted it, but Smallest > Bigger.

PD: How can i return players if i must use indexed tables?

Link to comment

Guys, if anyone need it, i solved it this way, not sure if it is efficient thought:

  
PTableValues = {} 
PTableValues["PlayerA"] = 50 
PTableValues["PlayerB"] = 45 
PTableValues["PlayerC"] = 55 
  
PTable = {} 
table.insert(PTable, 50) 
table.insert(PTable, 45) 
table.insert(PTable, 55) 
  
table.sort(PTable, function(a,b) return a>b end) 
  
for i,v in ipairs(PTable) do 
for k,s in pairs(PTableValues) do 
if v == s then 
outputServerLog("Player: "..k.." is Pos: "..i.." with value "..s .."/"..v) 
end 
end  
end 

EDIT: This will only return the last player, why?

PTableValues = {} 
PTableValues["PlayerA"] = 50 
PTableValues["PlayerB"] = 45 
PTableValues["PlayerC"] = 55 
  
PTable = {} 
table.insert(PTable, 50) 
table.insert(PTable, 45) 
table.insert(PTable, 55) 
  
table.sort(PTable, function(a,b) return a>b end) 
  
  
for i,v in ipairs(PTable) do 
for k,s in pairs(PTableValues) do 
if v == s then 
TableReturn = {} 
TableReturn[k] = i 
end 
end  
end 
  
for i,v in pairs(TableReturn) do 
outputServerLog("Player: "..i.." is pos: "..v) 
end 

Link to comment

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...