Why is this loop only looping twice even though the length of array is three at the start? [closed]
Asked by
6 years ago Edited 6 years ago
I am working on debugging an algorithm I wrote and part of it has an error that is incomprehensible to me. The only way I discovered it was by printing, because it was not throwing any errors in the output. Before getting to deep into this issue I would like to mention that EgoMoose
already solved my issue by recommending table.sort()
and using both the first and second argument. That being said, I would still like to find out why my function was not working as intended. I don't think that this first function I will post has any relationship to the problem, but I will post it just to make sure (and satisfy the curious among you all). Note: I will likely be changing a lot of these functions because EgoMoose
revealed the incredibly useful second parameter of table.sort()
. I just want to find out the elusive logic error in my code so that I do not repeat it in the future. Here is the first function:
01 | local function findMatches(recipes, inputDictionary) |
08 | local newRecipeList = { unpack (recipes) } |
13 | local matchesList = { } |
14 | for i, recipe in pairs (newRecipeList) do |
15 | local ingredientsList = recipe.Ingredients |
20 | if ingredientsList then |
21 | local matchesAmount = 0 |
22 | for i,v in pairs (ingredientsList) do |
23 | if inputDictionary [ i:lower() ] then |
24 | matchesAmount = matchesAmount + 1 |
27 | if matchesAmount > 0 then |
28 | recipe [ "Amount" ] = matchesAmount |
29 | table.insert(matchesList, recipe) |
33 | return sortByLargest(matchesList) |
As far as I know it is working correctly. The function that causes me the most problems is this one:
01 | local function sortByLargest(array) |
03 | local greatestArray = { } |
06 | local indexOfGreatestSoFar, greatestSoFar = next (array) |
07 | for i,v in pairs (array) do |
08 | print (v.Amount.. " " ..v.Name) |
25 | if v.Amount > greatestSoFar.Amount then |
27 | indexOfGreatestSoFar = i |
30 | table.insert(greatestArray, greatestSoFar) |
31 | array [ indexOfGreatestSoFar ] = nil |
33 | return sortByUpvotes(greatestArray) |
I hope that you can spot some kind of error or something in that function of mine. The structure of the recipes array that is passed as an argument to the recipes parameter is thus:
01 | local exampleListOfRecipeTypes = { |
03 | [ "Name" ] = "Beef and Cheese" ; |
12 | [ "Name" ] = "Beef Cheese" ; |
16 | [ "Beef" ] = "2 pounds" ; |
21 | [ "Name" ] = "Beef and flower" ; |
I would appreciate any insight on this matter. Note that an alternative solution has already been given by EgoMoose
. I just want to find the elusive logic error in my code. Thanks!