Are there any Issues / Redundancies in this code?

I just finished scripting a quick script that uses Remote Events to communicate enabling or disabling humanoid state types on and off and was wondering if there was any issues or unnecessary code I included in the script, or if there was any way to clean it up. Some of the phrasing with the warns might not make sense but they were just there for testing purposes.

Here’s the code

local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Defines the ReplicatedStorage Service
local Event = ReplicatedStorage.PlayerSetState -- Defines the PlayerSetState Event

local Character = script.Parent -- Defines Player Character
local Humanoid = Character.Humanoid or Character:WaitForChild("Humanoid") -- Defines Humanoid

Event.OnClientEvent:Connect(function(State, Boolean) -- Fires upon Receiving Event from Server
	if typeof(State) == "EnumItem" and State.EnumType == Enum.HumanoidStateType then -- Checks that the State Variable is a HumanoidStateType EnumItem
		if typeof(Boolean) == "boolean" then -- Checks that the Boolean Variable is a Boolean Value
			Humanoid:SetStateEnabled(State,Boolean) -- Enables/Disables HumanoidStateType according to Boolean Value
		else
			warn("Boolean (Variable 2) Passed to the Client in PlayerSetState RemoteEvent is not a Boolean Value!") -- Prints a Warning in Developer Console for Debugging Purposes
		end
	else
		warn("State (Variable 1) Passed to the Client in PlayerSetState RemoteEvent is not a HumanoidStateType EnumItem!") -- Prints a Warning in Developer Console for Debugging Purposes
	end
end)

instead of nesting your ‘good’ logic within a bunch of code blocks, consider escaping the ‘bad’ logic to make it cleaner to read. Something like:

Event.OnClientEvent:Connect(function(State, Boolean) -- Fires upon Receiving Event from Server
    if typeof(State) ~= "EnumItem" or typeof(Boolean) ~= "boolean" then return end
    --could also add your other check like:
   if State.EnumType ~= Enum.HumanoidStateType then return end
   --as after the first escape, you know State is properly a EnumItem
    --anything after this will run normally if the function didn't escape
end)

You might want to just assert the datatype in the parameters itself:
...function(State : EnumItem, Boolean : boolean)...

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.