Lesson 6 of 10
Any number of arguments
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
The three dots ..., select and table.pack
Explanation
A function that doesn't know in advance how many arguments it will get receives them with three dots: local function totalDamage(...). ... isn't a table but a series of values, which you can pass on as is to another function, as in string.format(fmt, ...), or count with select("#", ...).
If you need them in a table, table.pack(...) collects them into one and stores their count in the field n. Its opposite is table.unpack(t), which unpacks a table into separate values, so you can pass a list to a function that expects arguments, as in math.max(table.unpack(scores)).
Watch out for nil. A missed hit arrives as nil, and you can't rely on # for a table that contains nil: #{10, 25, nil} gives 2, and ipairs stops at the first nil. select("#", ...) and .n, on the other hand, count everything that was passed.
Your task
Write totalDamage(...) so it returns the sum of the hits, ignoring nil values, and then the number of all attacks, missed ones included. Then write logf(fmt, ...), which returns the result of string.format with the same arguments, and maxOf(list), which returns the largest value in the table list using math.max.
Checks
6 checks- totalDamage adds up the hits and counts them
- A missed hit (nil) doesn't stop the sum
- A missed hit counts as an attack, even at the end
- With no arguments it returns zero and zero
- logf passes its arguments on to string.format
- maxOf unpacks the table and passes its values to math.max