Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do i make it so when i press a button it gets a new array from a table?

I don't know how to put this into words properly but i want it so when i press x the array gets added by 1 for example...



id = { "apple", "sad" , 202049 }
game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(key)
	if string.lower(key) == "x" then
	print(id[+1])	
	end
end)
	

console when i press x

apple

when i press it again

sad

I appreciate your help!

1 answer

✓ Accepted answer

You need a variable to keep track of the index in the array, like this:

id = { "apple", "sad" , 202049 }
index = 1
game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(key)
    if string.lower(key) == "x" then
        print(id[index])
        index = (index % #id) + 1
    end
end)

So, the first time it will run id[1] and increase index to 2. Then it will run id[2] and increase index to 3. Then it will run id[3] and wrap index to 1 (because 3%3 == 0) so that it can repeat this indefinitely.

3 comments

0

Thanks so much!

1

I'd also recommend looking into UserInputService or ContextAction service, as KeyDown and KeyUp are deprecated.

0

It was just an example my actual script uses gui buttons, But thanks for the tip!

This discussion is preserved as it was. New answers, comments, and votes are closed.