How would I select a random part whilst going through a whole table?

I want to go through a table, but instead of it going in a specific order… it goes in a random order.

i.e; table = {1,2,3,4,5,6,7,8}; result: 4,2,8,1,7,3,5,4,6

This is my current script.

["Random_Burst"] = {
		Description = "",
		Function = function(pyroName)
			local tblOfPyro = {}

			for _,Item in game.Workspace:FindFirstChild("Pyrotechnics"):GetDescendants() do
				if Item:IsA("Model") and string.lower(Item.Name) == string.lower(pyroName) then
					table.insert(tblOfPyro,Item)
				end
			end

			for _,Pyro in pairs(tblOfPyro) do
				coroutine.wrap(function()
					for _,Item in Pyro:GetDescendants() do
						coroutine.wrap(function()
							if Item:IsA("Sound") then
								Item:Play()
							end
							if Item:IsA("ParticleEmitter") and string.lower(Item.Name) == "p1" then
								Item.Enabled = true
								task.wait(.3)
								Item.Enabled = false
							end
						end)()
						task.wait(.05)
					end
				end)()
			end

		end,
	}

If it’s number-indexed, sort it with random numbers.

local parts = parent:GetChildren()
local max = #parts

local generator = Random.new()

table.sort(parts, function(_a, _b)
    return generator:NextInteger(1, 10) > generator:NextInteger(1, 10)
end)

Could you explain in detail how your script works…? i’m unfamiliar with table.sort, and random.new.

table.sort() sorts a table based on what is returned in the sorter function. true returned means the elements should be swapped, false means they should not.

Random.new() is a more updated pseudorandom generator. It’s like math.random(). the NextInteger() function returns a random integer between 1 and 10.

For each two elements in the table, the function passed to table.sort is applied. By comparing two random numbers, we are essentially creating a random chance the elements will be swapped. Following this method, we are randomly swapping the order of elements within the table.

Please let me know if you have any more questions regarding my code.

1 Like

that code might never finish
better example How to make a table be in a random order?

1 Like

I forgot about that, thanks. It could be fixed by tracking the number of sorts and then consistently returning false afterwards.

updated:

local passes = 0
table.sort(parts, function(a, b)
	passes += 1
	
	if passes >= 20 then
		return false
	else
		return generator:NextInteger(1, 10) > generator:NextInteger(1, 10)
	end
end)

Thanks for pointing that out!

or yeah just remove a random index and pop it on the end like the post you linked suggested…

1 Like

You can also use Random.new():Shuffle(). Something to keep in mind though is that the method throws an error when there are holes in the given table.

2 Likes