I have this table for example:
local tlabel = {{4,"D"},{2,"B"},{1,"A"},{3,"C"}}
How would i get the table with the lowest number of this table?
I have this table for example:
local tlabel = {{4,"D"},{2,"B"},{1,"A"},{3,"C"}}
How would i get the table with the lowest number of this table?
You can pass a custom sort function with table.sort
local tlabel = {{4,"D"},{2,"B"},{1,"A"},{3,"C"}}
local function customSort(left, right)
return left[1] < right[1]
end
table.sort(tlabel, customSort)
print(tlabel) -- {{1,"A"},{2,"B"},{3,"C"},{4,"D"}}
One way you could go at the problem is by looping through the table, then checking to see if the current number is lower than that last one checked, and storing the lower one into a variable.
Here’s an example that I turned into a function for easier understanding:
local tlabel = {{4,"D"},{2,"B"},{1,"A"},{3,"C"}}
function findLowestValue(tbl)
local lowestNumber = nil
local lowestIndex = nil
for i, data in pairs(tbl) do
local number = data[1]
local letter = data[2]
if not lowestNumber or lowestNumber > number then
lowestNumber = number
lowestIndex = i
end
end
return tbl[lowestIndex]
end
print(findLowestValue(tlabel)) -- returns {1,"A"}
This is the correct solution, to get the table which contains the smallest value you’d just index the first item of the array named “tlabel”.
Oh, i didn’t realize that, sorry for that.