How to multiply every value in a table with each other?

  1. What do you want to achieve?
    I want to multiply every number in a table with each other.
  2. What is the issue?
    I don’t know how to do it.

I tried to look for solutions on the dev forum but I didn’t found what I wanted

i hope someone know the answer for my quest.

Exaple:

local numbers = {10,20,50,10,20,30}

-- How to multiply them with each other like:
-- 10 * 20 * 50 * 10 * 20 * 30

local numbers = {10,20,50,10,20,30} -- your table
local result = 1 
 
for a, b in pairs(numbers) do -- loop through all numbers
    result=result*b -- multiply
end
3 Likes
local numbers = {10,20,50,10,20,30}

local multipliedvalue = numbers[1] *  numbers[2] *  numbers[3] * numbers[4] * numbers[5] * numbers[6]

Hello there,

By just looping through the table and multiplying them by each other you have a simple solution.

Example:

local numbers = {10, 20, 50, 10, 20, 30}

local result = 1

for _, number in pairs(numbers) do
    result *= number
end

You should get an idea out of the code below.

local numbers = {
	10,
	20,
	50,
	10,
	20,
	30
}

print(numbers[1] * numbers[2])

Basically, we getting the table and we are just multiplying the first and second number here.

That is a very ineffecient way of doing it as it would be too much work to write the indexes out manually for a large table.

result should start at 1 like @WheezWasTaken’s example

Sorry, that was my mistake. Thank you for quickly pointing it out!

Thank you guys for fast reply. @WheezWasTaken I think your example was the best, but thanks for other too.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.