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

How do you loop through a table but each time it loops it's looped in a different order?

Asked by 7 years ago
Edited 7 years ago

I'm working on a project where there are these lines of code that scroll through each player in game.Players, but in a certain order. Is there a way for that order to be random?

[EDIT] I hope this isn't too vague, but here's a simple script I made about the problem.

while true do
    for i,v in pairs (game.Workspace.Folder) do
        print(v.Name)
        -- I don't want it to go through the whole folder, but I want it to go through it in a random order.
    end
end
0
Please edit your question to include the script in question. Pyrondon 2089 — 7y

1 answer

Log in to vote
0
Answered by
brianush1 235 Moderation Voter
7 years ago

You could make a table of random indexes, and check if the index exists, to know to add it or not. Then, repeat that until the table has the correct length, and loop through. Example implementation:

function rpairs(Table)
    local function Contains(Table, Item)
        for i,v in ipairs(Table) do
            if v == Item then return true end
        end
        return false
    end
    local Result = {}
    local Indexes = {}
    repeat
        local Index = math.random(1, #Table)
        if not Contains(Indexes, Index) then
            table.insert(Indexes, Index)
        end
        until #Indexes == #Table
    for _, i in ipairs(Indexes) do
        table.insert(Result, Table[i])
    end
    return ipairs(Result)
end
-- iterate through table:
for i,v in rpairs(game.Workspace.Folder:GetChildren()) do
    print(v)
end
Ad

Answer this question