How to randomize the order a pairs loop loops through a table?

Hey all!
I need help with making a pairs loop loop through something randomly.

For example,

local table = {"haha", "banana", "i forgor"}
for _, v in pairs(table) do
	print(v)
end

It prints in the same order every time

haha
banana
i forgor

haha
banana
i forgor

How would I make it loop through the table randomly?
Thanks!

You can use :Shuffle, like so:

local coolTable = {"haha", "banana", "i forgor"}

local RNG = Random.new()
RNG:Shuffle(coolTable)

for _, string in coolTable do
	print(string)
end

Edit: This code has been edited to reflect a better method to shuffle a table

8 Likes