So recently, I came across a problem… I am making a combat system, and because, well, script kiddies, I need to check if anything is nil before proceeding. This is… kinda what that looked like:
if character then
if character.HumanoidRootPart then
if character.Humanoid then
-- and so on...
end
end
end
That gets ugly fast. So I made a creative workaround, which is much more readable! Using a pcall and assert, we can check if a bunch of values are nil or false. Like this:
local success, response = pcall(function()
assert(player.Character)
assert(player.Character:FindFirstChild('Humanoid'))
assert(player.Character:FindFirstChild('Humanoid').Health > 0)
assert(player.Character:FindFirstChild('Humanoid').RootPart)
end)
if not success then return end
Assert is to error if a value is nil or false. Pcalls will detect errors, and if there is one, the success variable will be false. So, if not success
, then return/stop the code!
Now, you don’t have to deal with a bunch of indents and end
s on end
s…
Hope this little tip helps clean up anyone’s code!