Suppose that I have a table:
0.8
0.7
0.9
0.5
And I want to get the index of 2 largest values, so in this case, it should return:
3 1
I am quite newbie with Lua, so any help is more than welcome.
Thanks a lot,
Suppose that I have a table:
0.8
0.7
0.9
0.5
And I want to get the index of 2 largest values, so in this case, it should return:
3 1
I am quite newbie with Lua, so any help is more than welcome.
Thanks a lot,
You can loop over a table using for loop (for i = 1, #tbl or for i, val in ipairs(tbl)) and keep track of the largest and second to large elements (you'll need to store first index and first value and second index with second value to check the value and save the index). After the loop is done, you get the indexes of the first and second largest elements. Keep in mind that when the first value is updated its old value may need to be checked against the second value.
Another option is to build an array of indexes and sort it based on the values (as the sort can take an optional comparator function):
local function indexsort(tbl)
local idx = {}
for i = 1, #tbl do idx[i] = i end -- build a table of indexes
-- sort the indexes, but use the values as the sorting criteria
table.sort(idx, function(a, b) return tbl[a] > tbl[b] end)
-- return the sorted indexes
return (table.unpack or unpack)(idx)
end
local tbl = {0.8, 0.7, 0.9, 0.5}
print(indexsort(tbl))
This prints 3 1 2 4. If you only need the first two indexes, you can do local first, second = indexsort(tbl). Note that indexsort returns all indexes, so if you only need the first two (and your table is large), you may want to update the function to only return the first two items instead of the entire table.