|
| 10 Apr 2012 04:40 PM |
How do I find which key has the highest value?
Selected = {
Priority1 = 3 Priority2 = 1 Priority3 = 4 Priority4 = 2
} |
|
|
| Report Abuse |
|
|
NeonBlox
|
  |
| Joined: 19 Oct 2008 |
| Total Posts: 1462 |
|
|
| 10 Apr 2012 04:51 PM |
print(table.maxn(Selected)
The above line would print 3 because Priority3 is the largest. Since Priority3 is the third value, it returns 3.
If you want it to print 4, because it's the highest number. Use this.
var = 0
findLargest = function(tab) for _,v in pairs(tab) do if v > var then var = v end end return var var = 0 end
print(findLargest(Selected))
This would print "4". |
|
|
| Report Abuse |
|
|
| |
|
|
| 10 Apr 2012 04:59 PM |
"print(table.maxn(Selected)
The above line would print 3 because Priority3 is the largest. Since Priority3 is the third value, it returns 3."
Wrong. If you want the key, use this:
function largest(Tab) local largest, key; for _, v in pairs(Tab) do if largest then largest = largest>v and largest or v key = largest>v and key or _ else largest = v key = _ end end return key -- return key, largest -- return both key and largest number end |
|
|
| Report Abuse |
|
|
| |
|
NeonBlox
|
  |
| Joined: 19 Oct 2008 |
| Total Posts: 1462 |
|
|
| 10 Apr 2012 05:16 PM |
| Thank's agent. I was unsure. |
|
|
| Report Abuse |
|
|
|
| 10 Apr 2012 05:40 PM |
"Why use an underscore?"
Because I can. |
|
|
| Report Abuse |
|
|
jode6543
|
  |
| Joined: 16 Jun 2009 |
| Total Posts: 5363 |
|
|
| 10 Apr 2012 05:54 PM |
... Which wiki writer said that tables/arrays with non-numeric keys were called dictionaries?! *facenuke* |
|
|
| Report Abuse |
|
|