How to make a table be in a random order?

How do you put a table into a random order, or go through a table in a random order, instead of just going first to last?

2 Likes

how so? like in the doors game

Something like this? math.random(#table)

Edit: Sorry, replied to the wrong person

2 Likes

I don’t know why I didn’t think of doing that. That just picks out a random value in a table but I think I can figure out how to use it to randomize an entire table.

it’s really easy if that’s what you want, anyways see you good luck!

1 Like

Well what you could do is have a shuffle function which would look something like this:

local function shuffle(tableToShuffle: table): table
   local ShuffledTable = {}

   for Index = 1, #tableToShuffle do
      local RandomIndex = math.random(#TableToShuffle)
      table.insert(ShuffledTable , TableToShuffle[RandomIndex])
      table.remove(TableToShuffle, RandomIndex)
   end

   return ShuffledTable 
end
9 Likes

In place shuffle:

--Scramble the items in a set by swapping them with a random other item
--Sets of the same length scrambled with the same seed will be identical
--Scramble only up to 'limit' items, saves time if only a small selection out of a very large set is needed
local function Scramble(set, seed, limit)
	limit = limit or #set
	math.randomseed(seed)
	
	for i = 1, limit do
		local j = math.random(1, limit)
		local temp = set[i]
		set[i] = set[j]
		set[j] = temp
	end
	
	return set
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.