Reputation: 105
With a Lua table nested like this, how can I find the winning entry with the highest value? In other words, I would like to iterate over the table and get the answer "Banana."
[1] = {
['name'] = 'Apple',
['qty'] = 3,
},
[2] = {
['name'] = 'Orange',
['qty'] = 6,
},
[3] = {
['name'] = 'Kiwi',
['qty'] = 2,
},
[4] = {
['name'] = 'Banana',
['qty'] = 8,
},
Upvotes: 1
Views: 34
Reputation: 11171
This is a straightforward running maximum by looping over the table once while remembering associated sentinel data:
local t = {[1] = {
['name'] = 'Apple',
['qty'] = 3,
},
[2] = {
['name'] = 'Orange',
['qty'] = 6,
},
[3] = {
['name'] = 'Kiwi',
['qty'] = 2,
},
[4] = {
['name'] = 'Banana',
['qty'] = 8,
}}
local highest_qty, name = t[1].qty, t[1].name
for i = 2, #t do
if t[i].qty > highest_qty then
highest_qty, name = t[i].qty, t[i].name
end
end
print(name) -- Banana
Various variants of this exist, potentially using ipairs
, introducing some local variables, using a default value of -math.huge
and a default name of nil
(if the table can be empty), etc.
Upvotes: 2