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

How would I make a pairs loop go in a random order?

Asked by
LazokkYT 117
2 years ago
Edited 2 years ago

Hi. How would I make a pairs loop go in a random order? For example, if I do:

for _,v in pairs(game.Workspace:GetChildren()) do
    print(v.Name)
end

It prints:

Terrain

Camera

Part

If I execute the command again, it prints in the same order. That's the issue. How would I go about making it random? Just a reminder, I'm not trying to pick a random child, I'm trying to make it print out of order as in complete randomness. Thank you!

1 answer

Log in to vote
1
Answered by 2 years ago
Edited 2 years ago

If you want to choose random indicies from an array, generally the best solution is to randomize the array before the iteration. There are many algorithms for randomizing, or "shuffling" arrays, the most popular probably being the Fisher–Yates shuffle.

Here's a Lua implementation:

local function randomize(t)
    local _t = {}

    -- make a copy of the original table
    for i = 1, #t do 
        _t [i] = _t [i]
    end

    -- shuffle the copied table randomly
    for i = #_t, 2, -1 do
        local j = math.random(i)
        _t[i], _t[j] = _t[j], _t[i]
    end

    return _t
end

Now, you just have to pass your array through this function then iterate over the result as you would normally. For example:

for _, v in next, randomize(workspace:GetChildren()) do
    print(v)
end

Let me know if you have any questions.

Ad

Answer this question