Need help with In Pairs Loop

Hello!
I have a script that shows images whenever I click a button and disappear afterwards. I have compiled different images I want to pop up whenever the button is clicked through a table but since I’m using an in pairs loop, it follows the same order and changes to all five of the images every time I click the button. Is there a way for when the Gui button is clicked only one image (chosen randomly from the table) will appear and disappear afterwards?

My idea is similar to simulator games that has a small Gui that pops up whenever you click your mouse using a gear in game but this time, I want one from the images I’ve gathered to pop up when the button is clicked in random order.

(I’m not yet done with the script but it contains the things needed)
Here is my script:

local Players = game:GetService("Players")
local gui = Players.LocalPlayer:WaitForChild("PlayerGui")
local button = gui["Itsuki Clicker"].ItsukiButton.Itsuki.ImageButton
local debounce = true
local genNum = 0
local itsukiReactions = game:GetService("ReplicatedStorage")["Itsuki Reactions"]

local iTable = {itsukiReactions.ItsukiBlank,
	itsukiReactions.ItsukiMad,
	itsukiReactions.ItsukiScared,
	itsukiReactions.ItsukiShocked,
	itsukiReactions.ItsukiShout
}

button.MouseButton1Click:Connect(function(clicked)
		for _, v in pairs (iTable) do
			genNum = genNum + 1
			local new = v:Clone()
			local newName = v.Name..genNum
			new.Parent = game.Players.LocalPlayer.PlayerGui["Itsuki Clicker"].Itsuki1
			wait(0.2)
			new:Destroy()
		end
end)

I’m not sure what you are trying to say here. If you mean you want to iterate through the table in the order you placed the images then use ipairs instead of pairs. pairs does not iterate through tables in order, it iterates through key value pairs instead.

Your script is kind of confusing, but I believe you want to randomize the list. To do this use this function in your code to shuffle the array:

local function Shuffle(t)
	for i = 1, #t do
		local j = math.random(#t)
		t[i], t[j] = t[j], t[i]
	end

	return t
end

So with this in your code all you have to do is replace

for _, v in pairs (iTable) do

with

for _, v in ipairs(Shuffle(iTable)) do
1 Like

Thank you! Now it’s randomized :smiley: Now that’s solved, sorry if this may seem too much, do you have any idea on how to stop the loop once it picks one value from the randomized list?

In this case you don’t even need to use a loop. You can just use

local new = iTable[math.random(#iTable)]:Clone()
1 Like