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

Is there a built-in function to randomize lists/tables?

I'd rather just call some randomize function on a list than have to create the function myself.

3 comments

0

You could of looked it up, there IS a search bar on the top of the screen anyway. There is also google, and roblox wiki.

1

Lord, some people ask because they found nothing and just want to confirm that there is nothing.

0

Well, just let the Moderation thing expire.

2 answers

✓ Accepted answer

Unfortunately, Lua does not have any built-in implementation of shuffle algorithms.

However, there are some easy ones that you can implement or find.

The Fisher-Yates shuffle algorithm is an efficient, reliable, and easy-to-implement algorithm for array randomization.

Here is my optimized implementation of Fisher-Yates in Lua. Feel free to use it as you wish. All you have to do is put the function somewhere and call it on a table in array form that you want to shuffle.

function shuffle(array)
    -- fisher-yates
    local output = { }
    local random = math.random

    for index = 1, #array do
        local offset = index - 1
        local value = array[index]
        local randomIndex = offset*random()
        local flooredIndex = randomIndex - randomIndex%1

        if flooredIndex == offset then
            output[#output + 1] = value
        else
            output[#output + 1] = output[flooredIndex + 1]
            output[flooredIndex + 1] = value
        end
    end

    return output
end
math.randomseed(tick()) -- be sure to set randomseed somewhere for better randomness

1 comment

0

Thanks!

There is no built-in function for randomizing a table. However, after a bit of research, I came across a script stickmasterluke posted.

The script essentially takes the values of a table, puts them in a new table in a random order using math.random and returns the new table once it's done. It even has example usage so you can figure out how it works.

You can take the script from here.

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