I am trying to make an admin ranking system of sorts, and I want to know how to make it so if the target is not in the game, it will not error. Here is the code I am currently using that errors when OtherPart is not in the game.
local targets = {workspace.Part, workspace.OtherPart} for i,target in pairs(targets) do target:Destroy() end
Any help?
You can wrap any function in pcall()
, a Lua function that effectively "tries" to execute the code within it like Java and JavaScript's try
keyword. If you're not concerned about the error message (you probably aren't since you know what it will most likely be), you can just do this:
pcall(function() local targets = {workspace.Part,workspace.OtherPart} for i = 1,#targets do targets[i]:Destroy() end end)
You can also use if
statements to create a more conservative approach that does not require using the pcall
function:
local targets = {workspace:FindFirstChild('Part'),workspace:FindFirstChild('OtherPart')} for i = 1,#targets do if targets[i] then targets[i]:Destroy() end end