Multiplying table of numbers by X number

Hello! I am trying to create a table of numbers ranging from 100 - 500 and multiply them by 3. Yes I have gotten the code below to work but when the code multiplies anything after 100 it seems to multiply it again? For Example: 3x100 = 300 and 3x200 = 600 etc… Yet it’s giving me 60,000 instead of 600 if anyone could maybe help me out I’d Appreciate it!

local Numbers = {100, 200, 300, 400, 500}
local result = 3

for a, b in pairs(Numbers) do
	result = result * b
	
	print(result)
end
2 Likes

You are multiplying all the numbers in the table together and also by 3.

2 Likes

I think what you should use instead is something like this:

local function multiplyBy(table_obj, number) -- take 
    local result = {} -- Create a new one
    for i,num in ipairs(table_obj) do -- Loop through the positions (i) and values (num)
        table.insert(result, num*number) -- Multiply that value by the number that was given as input in the function (number) and insert it into the result table
    end
    return result -- return our new table
end

local Numbers = {100, 200, 300, 400, 500}
local output = multiplyBy(Numbers, 3) -- We call the function with our initial table and the number we want to multiply every digit by.

This should work perfectly fine.

1 Like

Thank you! I think I realized after what azqjanna had said, I was looping though them all and Multiplying all of them by 3 my mistake!

1 Like

Hi, sorry to bump a solved thread but I wanted to show how the script you originally posted can be modified to work how you wanted, in case someone else is wondering what exactly was wrong and can’t see it from receipes’ nice and reusable solution:

local Numbers = {100, 200, 300, 400, 500}
local multiplier = 3
for key, number in pairs(Numbers) do
	local result = number * multiplier
	Numbers[key] = result
	print(result)
end

I also changed the iterator variables to something more descriptive, but keep in mind that just like other variables, they don’t need to have any specific name to work as long as the rest of the script is adapted to use the same names.

1 Like

A nice way to do it as well(albeit kinda overcomplicated and unnecessary) is to use metatables to do it, something like this:

local Metatable = {
__mul = function(Table, Value)
for Key,Number in pairs(Table) do
	Table[Key] = Number * Value
end
return Table
end
}

function SetArithmetic(Table)
return setmetatable(Table, Metatable)
end


local Nums = SetArithmetic({2, 5, 8})
print(Nums * 3) --Prints {6, 15, 24}

Maybe this is useful in a module script if you are gonna use it in many scripts. It’s of course possible to add the add, sub, div, mod, pow and unm operators.

2 Likes

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