1
votes

I'm still learning lua and the pairs function is great, but i clearly don't get how to use it properly:

I'm trying to count the total of a value in a nested table, based on its first value, not key.

I have a table:

arr = {}
arr[100] = {1, "alpha", 4}
arr[10740] = {1, "bravo", 6}
arr[26104] = {2, "charlie", 7}
arr[150] = {3, "delta", 1}
arr[1006] = {2, "echo", 0}
arr[91002] = {1, "foxtrot", 2}
  • k is a random attribute - odd for a key but i has to be this way
  • v[1] is group ID,
  • v[2] is group name,
  • v[3] is number in group

Now i can use the pair function to count the total of v[3] in the table:

count = 0
for k, v in pairs(arr) do
count = count + v[3]
end;
print count

What I need to be able to do is calculate the total of v[3] grouped by v[1]. In he table v[1] is a fixed number of 1-16 but there is can be different amounts of them.

but need an outcome of something like:

  • Group 1 = 12
  • Group 2 = 7
  • Group 3 = 1

I can achieve it by creating separate tables, taking all the values out that are in group 1 and then using the above - but i feel if like there must be a better way.

Many thanks in advance.

1

1 Answers

2
votes

You are on the right way, you need extra table to store count per group:

local group_count = {}
for k, v in pairs(arr) do
  group_count[v[1]] = (group_count[v[1]] or 0) + v[3]
end

-- not sorted output
for k, v in pairs(group_count) do
  print('Group '..k..' = '..v)
end