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

How to limit the number of players inside this table?

This is something simple but I always get confused when it comes to table, here I made a script which will add the name of the players who clicks a button in a table, but I wanted to limit it to 5 players, how could I do this?

local player = game.Players.LocalPlayer

local Button = script.Parent

local t = {}

Button.MouseButton1Click:Connect(function()
	table.insert(t, 1, player.Name)
	print(t[1].. " has been added to the table.")
end)

2 answers

✓ Accepted answer

Hi Duke,

You could simply do this using an if statement. It would look something like this:

local player = game:GetService("Players").LocalPlayer
local button = script.Parent
local t = {}

Button.MouseButton1Click:Connect(function()
	if not #t < 5 then -- If they are not smaller than 5
		table.insert(t, #t + 1, player.Name)
		print(t[#t].. " has been added to the table.")
	end
end)

##You can find out more about if statements here.

Thanks,

Best regards,

IdealistDeveloper

Hello DukeOfWorms! Try this:

local player = game.Players.LocalPlayer

local Button = script.Parent
local Text = script.Parent.Parent.TextLabel

local addedPlayers  = 0

local t = {}

Button.MouseButton1Click:Connect(function()
	if #t <= 5 then
		table.insert(t, addedPlayers + 1, player.Name)
		print(t[addedPlayers + 1].. " has been added to the table.")
		addedPlayers = addedPlayers + 1
	end
end)

When the button is pressed, it checks if the stuff in the table is less or equal then 5. If so, it inserts a player into the table with its index as the addedPlayers variable plus 1. Then it adds 1 to the addedPlayers variable. Hopefully, this helps. Make sure to accept this answer if it does.

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