Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Arithmetic operations in a table?

Asked by 5 years ago

For my game i want to calculate the average of the numbers found in a table. So to do this, I have to add all of them and divide it by the number of values. I know how to do that last part (#table), but I have no idea where to start to be able to add all the values of the table together.

1 answer

Log in to vote
0
Answered by 5 years ago
Edited by ScriptGuider 5 years ago

well you could just do this:

local values = {10,20,40,5,12,34,78} -- change the values in here

function average(array)
    local current_value = 0

    for _,number in pairs(array) do
        current_value = current_value + number
    end

    return current_value/ #array
end

local aver = average(values)
print(aver)

change the values in the values table to the desired values

Ad

Answer this question