Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Manipulating a local table without changing the original?

Say I have a script that randomizes colors where no two colors are the same:

local colors = {"Bright blue","Bright red","Bright yellow"}
local part = workspace.Part

while true do
for i = 1, #colors, 1 do
local ran = math.random(1,#colors)
part.BrickColor = BrickColor.new(colors[ran])
table.remove(colors,ran)
wait(1)
end
end

The problem here is when the code is run again, the table will run out of colors. Now thinking logically, you'd think you can just make a local variable that is assigned the value of the table colors.

local colors = {"Bright blue","Bright red","Bright yellow"}
local part = workspace.Part

while true do
local c = colors
for i = 1, #c, 1 do
local ran = math.random(1,#c)
part.BrickColor = BrickColor.new(c[ran])
table.remove(c,ran)
wait(1)
end
end

Tables, however, work differently than normal variables. If you change c, then it also manipulates the table colors. How would I prevent from changing the value of colors? I now I can redefine colors as a table full of colors in the while loop, but that won't work in other situations where I need specific data untouched,

1 answer

✓ Accepted answer

Create another table such as so:

local colors = {"Bright blue","Bright red","Bright yellow"}
local part = workspace.Part

while true do
local c = {unpack(colors)} -- Contents Put Into Array 'c'
for i = 0, #c, 1 do
local ran = math.random(1,#colors) -- Shouldn't this be #c?
part.BrickColor = BrickColor.new(c[ran])
table.remove(c,ran)
wait(1)
end
end

1 comment

1

Thanks, I didn't know about "unpack". Line 7 should use #c instead of #colors. Thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.