How would I add all values of a table together?

Hi, I’m trying to learn the usage of tables, and I’m trying to figure out a way to add all values of a table without having to declare which values I want to add.

Basically, I’m trying to find a way that is faster than simply saying v[1] + v[2] + v[3]… so on.

local TABLE = {
    apple = {1, 3},
    bread = {3, 2}
}


for i, v in pairs(TABLE) do
    -- i = apple/bread
    -- v = numbers
    print(v[1] + v[2]) -- prints 4, 5

end

Based on your example code you provided, I think this is what you want?

local TABLE = {
    apple = {1, 3},
    bread = {3, 2}
}



for _, Values in pairs(TABLE) do --As we don't need the first value, just set it to an _.
    Total = 0 --Keep a running total
    for _, number in pairs(Values) do --Run the following code for every number set to apple, bread, ect.
              Total = Total + number --Add the value of the number to the running total
    end
    print(Total) --print the running total
end

Output:
4
5

Is that what you wanted to achieve?

1 Like