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

How do I randomize for i, v in pairs?

Asked by
Songist 49
5 years ago
        for i,v in pairs(script.Parent:GetChildren()) do
            if v:IsA("Part")then
                v.BrickColor=BrickColor.Random()
        wait(1)
    end
end

Just a simple script to change a bunch of bricks with a 1 second delay between them. My problem is that it goes in the same order every time. What method should I go about in randomizing this? Thank you!

0
Like? You need to explain more. I don't really understand the problem. voidofdeathfire 148 — 5y
0
There are bricks that change color/properties, gathered through getchildren(). The bricks are listed in the same order, so they each undergo the change in the same order. I want to randomize this. Songist 49 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago

Here's a Shuffle function that I've found quite useful:

function Shuffle(list)
    for i = 1, #list-1 do
        local index = math.random(i, #list)
        list[i], list[index] = list[index], list[i]
    end
end

Shuffle the children before iterating over it and it'll be different every time. Either make sure to use math.randomseed(tick()) in one place in one script or change the code to use Random.

0
Thank you! Got it working! Still a bit confused what the function does though. What is line 4 doing? Thanks again! Songist 49 — 5y
0
Multiple assignment; it's switching the values in the list. ex, if i = 1 and index = 3, it'll switch the first and third values - this effectively puts a random value from the list at the beginning of the list, then repeats for each index (except the last). chess123mate 5873 — 5y
Ad

Answer this question