Question

Here is a short program that takes in a table, and returns the index of the largest numerical value in the table.

My question is - can someone explain to me the "word, count" in the for loop on line 5? The program works, but I am not understanding how the word, count in the for loop does anything.

 numbers = {10, 5, 1}

 function largest(t)
   local maxcount = 0
   local maxindex
   for word, count in pairs(t) do
     if count > maxcount then
       maxcount = count
       maxindex = word 
     end
   end
   return maxindex, maxcount
 end

 print(largest(numbers))
Was it helpful?

Solution

Running the following code should make it more clear:

tbl = { a = "one", b = "two", c = "two and half" }
for key, val in pairs(tbl) do print(key, val) end

When you run pairs in a for loop, it executes the code between do and end once for each key/value pair in the table; for x, y in sets the names of the key and value for the code within the loop. pairs is the most commonly seen example of an iterator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top