Here is my code for a simple program that finds the largest number in a table, and returns the number and it’s index. My problem is that the program isn’t working with negatives.
numbers = {1, 2, 3}
function largest(t)
local maxcount = 0
local maxindex
for index, value in pairs(t) do
if value > maxcount then
maxcount = value
maxindex = index
end
end
return maxcount, maxindex
end
print(largest(numbers))
This piece of code prints out “3 3”. The largest number is 3, and it is in the 3rd position. When i set numbers to something like {-1, -2, -3} it returns “0 nil” instead of “-1 1”.
Thanks!
Your default values are wrong.
They should be
You were receiving “0 nil” because
maxindexis undefined until the if conditionvalue > maxcountis true.the default
maxcountvalue was 0 and that’s bigger than all the negative numbers.