Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How can i compare table elements among themselves?

Asked by 4 years ago
Edited 4 years ago

For example. i have a table

t = {Variant1 = 33, Variant2 = 1, Variant3 = 123, Variant4 = 33}

I need to find the key(s) with highest value(s). So, how can i compare it?

2 answers

Log in to vote
1
Answered by
rabbi99 714 Moderation Voter
4 years ago

This is how I always do it.

01local highest = 0
02local t = {Variant1 = 33, Variant2 = 1, Variant3 = 123, Variant4 = 33}
03 
04for i,v in pairs(t)do
05    if v > highest then
06        highest = v
07    end
08end
09 
10print(highest)
0
But what if i have 2 same highest? for example var1 = 2, var2 = 5, var3 = 5. I need to randomize the choose between same numbers. Gulgazar 65 — 4y
1
then you can add them to a table and then math.random(1,#Table Zero_Tsou 175 — 4y
Ad
Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

This is the most(maybe) solution I can found:

1local t ={1, 2, 3}
2 
3print(math.max(unpack(t)))

About the randomize, why you need to randomize it when it already the same?

0
Not sure if i need exactly this method, but seems it's useful in other situations, so i'll remember it, thank you! Gulgazar 65 — 4y

Answer this question