This code is worrying for several reasons.
Your names are bad. It should be possible to guess what code does without reading the code definitions.
What might add() possibly do? I have no idea. A better name would be updateRacingPlayers().
What might plr possibly hold? Not a player, as it turns out; because it's a list. Contracting (already short!) words is a bad idea
plr is a worrying global variable. I'm guessing you simply want it to always hold all of the players currently on the pink team.
In that case, there's no reason for it to be a global variable modified all over the place.
Just refer to game.Teams.Racing:GetPlayers() when you need the list of players currently on that team -- but you should be returning it from your function, not modifying a global variable.
You should use generic for loops almost always. The for i = 1, ... loops only really have a place in repeating something N times.
I suggest using str:sub(...) instead of string.sub(str, ...) because it's easier to read and shorter.
You really shouldn't use unnecessary ( ) in your conditions.
Using ~= nil is redundant in a condition. Don't say that unless you mean it (i.e., you need to differentiate between false and nil)
After applying the above fixes, your code becomes this:
function getRacingPlayers()
return game.Teams.Racing:GetPlayers()
end
function update()
for _, part in pairs(script.Parent:GetChildren()) do
if part.Name:sub(1, 5) == "Yield" then
part.SurfaceGui.TextLabel.BackgroundTransparency = 1
part.SurfaceGui.TextLabel.Text = ""
end
end
for i, player in ipairs(getRacingPlayers()) do
item = script.Parent:FindFirstChild("Yield" .. tostring(i)).SurfaceGui.TextLabel
if item then
item.BackgroundTransparency = 0
item.Text = player.Name
end
end
end
spawn(function()
while wait() do
update()
add()
end
end)
There are several things off about this code.
First, item cannot be nil; item is a TextLabel. If the TextLabel didn't exist, you would get an error, not nil.
You probably mean to be checking the :FindFirstChild. In your code, if that returned nil, asking for its .SurfaceGui would throw an error.
Instead, you have to write the condition like this:
for i, player in ipairs(getRacingPlayers()) do
local yield = script.Parent:FindFirstChild("Yield" .. tostring(i))
if yield then
local item = yield.SurfaceGui.TextLabel
item.BackgroundTransparency = 0
item.Text = player.Name
end
end
There may be other problems with your code, but this version should be much easier to work with and debug.
1 comment
You don't need "tostring" on line 22. Lua will automatically convert it to a string when you concatenate.