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 a for i loop, like so:

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

local randomizedTable = {}

for i = 1, #coolTable do
	local index = nil
	
	repeat 
		index = coolTable[Random.new():NextInteger(1, #coolTable)]
	until not table.find(randomizedTable, index)
	
	table.insert(randomizedTable, index)
end

for i, string in ipairs(randomizedTable)  do
	print(string)
end
7 Likes