Hi,
I need to easily compare int, that i get returned name of the bigger int (ints are stored in table).
So like compare the size of a string? You can use the #
operator or string.len()
like so:
local cheese = "cheese"
local ham = "ham"
print(#cheese > #ham) --true
print(string.len(cheese) < string.len(ham)) --false
No, i need to compare size of int, and return name of the bigger one (sry, i wrote it badly) (i store them in array
local array={["int1"]=0,["int2"]=0}
)
You’re indexing with non-numerical values in that table, so I believe it’s a dictionary.
yes, i named it table, but its dictionary
If you use an array instead of a dictionary, you can sort the values out and return either the first or the last element of the array for your integer. You probably don’t need a dictionary here.
local ints = {5, 2, 6, 1, 3, 4}
table.sort(ints)
print(ints[1], ints[#ints])
This sorts from lowest to greatest as per the default behaviour of table.sort. You can specify a comparison function if you want to do this differently.
If you do use a dictionary, that changes your requirements. You’ll have to iterate all the elements and perform a comparison from the current value and the previous index.
but i need to get the name of biggest, not its value (changing dictionary to array isnt problem)
Here’s a little example of how you could do so:
function getBiggestIndex(dictionary)
local biggest = -math.huge
local biggestIndex
for index, value in pairs(dictionary) do
if value > biggest then --compare the value with the last biggest
biggest = value
biggestIndex = index
end
end
return biggestIndex
end
local dictionary = {
int1 = 3,
int2 = 4,
int3 = 2
}
local biggestIndex = getBiggestIndex(dictionary)
print(biggestIndex, ", ", dictionary[biggestIndex]) --int2, 4
A general approach to finding some maximum value in a table goes as follows:
local maximumKey
local maximumValue = -math.huge
for key, value in next, data do
if value > maximumValue then
maximumKey = key
maximumValue = value
end
end
For the specific case of finding the largest integer in an array of integers, you can simplify this down without sorting the entire array:
local largest = math.max(unpack(data))