Help incorporating math.random into a table

Currently I have this script:


local sounds = {
	[1] = "MessWithMe",
	[2] = "E-Drone",
	[3] = "LawBreaker",
	[4] = "BetweenTheLines", 
}

while true do
	for i, soundName in pairs(sounds) do -- Using ipairs to guarantee order. Order with pairs is undefined behavior and I am not sure about the default iterator
		local lastSound -- Dirty hack, but it works!
		for _, speaker in workspace:WaitForChild("PreShow"):GetChildren() do
			if speaker:IsA("Part") then
				local sound = speaker:WaitForChild(soundName)
				sound:Play()
				sound.Volume = 0.2
				lastSound = sound
			end
		end
		lastSound.Ended:Wait()
	end
end

How can I incorporate math.random into this script, so when the script runs, it will randomise the order of which the songs play in.

thanks in advance :grinning:

1 Like

You can use this function for shuffling/randomizing arrays:

local function ShuffleArray(array)
	local newArray = table.clone(array)
	
	for i = #newArray, 2, -1 do
		local j = math.random(i)
		newArray[i], newArray[j] = newArray[j], newArray[i]
	end
	return newArray
end

This function does not modify the original table, but instead creates a new one based from it.

Where would I put this inside my current script?

1 Like
local sounds = {
	[1] = "MessWithMe",
	[2] = "E-Drone",
	[3] = "LawBreaker",
	[4] = "BetweenTheLines", 
}

local function ShuffleArray(array)
	local newArray = table.clone(array)
	
	for i = #newArray, 2, -1 do
		local j = math.random(i)
		newArray[i], newArray[j] = newArray[j], newArray[i]
	end
	return newArray
end

while true do
	for i, soundName in pairs(ShuffleArray(sounds)) do -- Using ipairs to guarantee order. Order with pairs is undefined behavior and I am not sure about the default iterator
		local lastSound -- Dirty hack, but it works!
		for _, speaker in workspace:WaitForChild("PreShow"):GetChildren() do
			if speaker:IsA("Part") then
				local sound = speaker:WaitForChild(soundName)
				sound:Play()
				sound.Volume = 0.2
				lastSound = sound
			end
		end
		lastSound.Ended:Wait()
	end
end

Edit: Updated function to use table.clone()

1 Like
local sounds = {
	[1] = "MessWithMe",
	[2] = "E-Drone",
	[3] = "LawBreaker",
	[4] = "BetweenTheLines", 
}

local currentlyPlayingSound; 

while true do
	for _, speaker in workspace:WaitForChild("PreShow"):GetChildren() do
		if speaker:IsA("Part") then
            local randomSound = (function()
                local sound;
                repeat
                    sound = sounds[math.random(1, #sounds)]
                until sound ~= currentlyPlayingSound
                
                return sound
            end)()
			local sound = speaker:FindFirstChild(randomSound)
			sound.Volume = 0.2
			sound:Play()

			currentlyPlayingSound = sound
		end
	end

	currentlyPlayingSound.Ended:Wait()
end
1 Like

tysm!!! it works, and functions as intended! :grin:

1 Like

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