Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the largest value in a table

How can I get the largest value in a table in Corona SDK/Lua?

For example, I have this table:

local table = {
   ["item1"] = 10,
   ["item2"] = 20,
   ["item3"] = 30,
   ["item4"] = 40,
   ["item5"] = 50
}

I have to get item5 and its value 50 as the answer.

like image 487
jettplaine Avatar asked Jul 04 '26 11:07

jettplaine


1 Answers

local max_val, key = -math.huge
for k, v in pairs(your_table) do
    if v > max_val then
        max_val, key = v, k
    end
end
print(key, max_val)
like image 97
Egor Skriptunoff Avatar answered Jul 07 '26 09:07

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!