Certainly! To optimize the given code, we'll perform the following steps:
- Avoid redundant calls to
game:GetService.
- Cache repeated access to properties and services.
- Clean up the code for readability and efficiency.
Here's the optimized version:
local function Check(Player)
local Players = game:GetService("Players")
local Whites = {}
local Blacks = {}
local function getSkinColor(player)
local bodyColors = player.Character and player.Character:FindFirstChildOfClass("BodyColors")
if bodyColors then
return bodyColors.HeadColor3
end
return nil
end
local function classifySkin(color)
if color then
local brightness = math.sqrt(0.241 * color.r^2 + 0.691 * color.g^2 + 0.068 * color.b^2)
if brightness <= 0.4 then
return "Black"
elseif brightness >= 0.6 then
return "White"
end
end
return nil
end
if Player then
local color = getSkinColor(Player)
return classifySkin(color)
else
for _, player in ipairs(Players:GetPlayers()) do
local color = getSkinColor(player)
local classification = classifySkin(color)
if classification == "Black" then
table.insert(Blacks, player)
elseif classification == "White" then
table.insert(Whites, player)
end
end
end
return Whites, Blacks
end
local WhitePeople, BlackPeople = Check()
print("Whites:")
for _, player in ipairs(WhitePeople) do
print(player.Name)
end
print("Blacks:")
for _, player in ipairs(BlackPeople) do
print(player.Name)
end
print("Localplayer skin color:")
print(Check(game:GetService("Players").LocalPlayer))
Explanation of Optimizations:
-
Internal Function getSkinColor:
- This function fetches and returns the
HeadColor3 property of the BodyColors object of a player's character. If no character or BodyColors are found, it returns nil.
-
Internal Function classifySkin:
- This function calculates the brightness of the color and classifies it as "Black" or "White" based on the calculated brightness.
-
Optimization in Main Function:
- If
Player is passed, it fetches the skin color and classifies it directly.
- If no
Player is passed, it retrieves the list of all players, gets their skin colors, and classifies them accordingly.
-
Iterating Through Players:
- Uses
ipairs for efficient iteration.
- Populates
Whites and Blacks lists accordingly by checking skin brightness.
-
Printing Results:
- Loops through the tables to print player names for "Whites" and "Blacks".
This version of the function is more modular and maintains readability while being efficient.