How to get the average from a table when length not known

I have a table with 3-5 values depending.  So say I get table…

Table={5, 10, 15}

or

Table={5, 10, 15, 20, 25}

How can I find out what the average will be of all number elements?

how about something like this:

[lua]

local sum = 0

local ave = 0

local elements = #Table

for i = 1, elements do

    sum = sum + Table[i]

end

ave = sum / elements

[/lua]

or for a sparse table

local elements = 0 local sum = 0 local ave = 0 for k,v in pairs( Table ) do sum = sum + v elements = elements + 1 end ave = sum / elements

If you don’t even have a table (for instance, you’re getting the numbers out of a listener function), something like this:

local average, n = 0, 0 -- You need at least these -- stuff function MyFunc (value) average = average \* n -- Undo the most recent division (or pretend to, the first time)... average = average + value -- ...accumulate the new value... n = n + 1 -- ...update the count... average = average / n -- ...and the average. end

From your examples I doubt this is what you were after, but it’s what I first thought of when reading the subject, and I include it for completeness.

Just a complete side note, please don’t use “table” as a variable name.  “table” is an object that holds table processing functions.  I know the OP is using Table which is different than table, but it’s close enough that it’s easy to make a mistake.

Thank you

Rob

Awesome thanks everyone for help!

how about something like this:

[lua]

local sum = 0

local ave = 0

local elements = #Table

for i = 1, elements do

    sum = sum + Table[i]

end

ave = sum / elements

[/lua]

or for a sparse table

local elements = 0 local sum = 0 local ave = 0 for k,v in pairs( Table ) do sum = sum + v elements = elements + 1 end ave = sum / elements

If you don’t even have a table (for instance, you’re getting the numbers out of a listener function), something like this:

local average, n = 0, 0 -- You need at least these -- stuff function MyFunc (value) average = average \* n -- Undo the most recent division (or pretend to, the first time)... average = average + value -- ...accumulate the new value... n = n + 1 -- ...update the count... average = average / n -- ...and the average. end

From your examples I doubt this is what you were after, but it’s what I first thought of when reading the subject, and I include it for completeness.

Just a complete side note, please don’t use “table” as a variable name.  “table” is an object that holds table processing functions.  I know the OP is using Table which is different than table, but it’s close enough that it’s easy to make a mistake.

Thank you

Rob

Awesome thanks everyone for help!