It is pretty common after we have a table filled with some data, we may want to do something with all these "elements" of a table. For tables with sequential numeric indices it seems easy with for
loop. Here is an example where we want to sum all elements:
numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
sum = 0
for i = 1,#numbers do
sum = sum + numbers[i]
end
print('Total is:', sum)
However, we now know that table may have non-numeric indices! How to deal with them? We shall learn in a minute. Moreover we shall learn about slightly more convenient approach even to iterating over tables with simple sequential indexing.
Regard the table containing salaries of employees. Employee names are used as keys:
salaries = {
['John M Carpenter'] = 1800,
['Jane L Puppetmaster'] = 2700,
['Jess W Beerman'] = 2150,
}
sum = 0
for name, money in pairs(salaries) do
print(name, 'earns', money, 'dollars')
sum = sum + money
end
print('In total they earn ' .. sum .. ' per month')
What new do we see here? The pairs(...)
function which takes some table as argument and then on every call returns
new pair of key
and value
from it. We assign such "key-value" pairs to name
and money
variables on every
iteration. Note slightly differing for
syntax with the word in
word in place of some equals sign.
Inside the function body we do two things: print the current name-salary pair - and then add the salary to the sum
variable. Try running it and the idea hopefully is obvious.
The same approach could be used with numeric indices!
However if your table has sequential indexing (i.e. from 1
, 2
, 3
up to size of the table) - it is advisable
to use ipairs
function. It has slight differences in behavior, which could be overlooked at the first glance:
1, 2, 4, 5
)pairs
).So we can rewrite our first example with modified loop:
for _, n in ipairs(numbers) do
sum = sum + n
end
Note that we don't need indices returned by ipairs
- only values are of interest. Hence we assign them to _
variable - it is usual way to mark that we don't care about whatever is assigned there.
For exercise please try solving Array Counters task. You'll see it mentions another problem, Vowel Count - which is simpler in that it doesn't require array but will make to recollect something about string operations - so it would be good to solve it too.