Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to limit the number of players inside this table?

Asked by 4 years ago
Edited 4 years ago

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

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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

Ad
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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.

Answer this question