Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to bypass errors of a ranking system not being in the game...?

Asked by
KDarren12 705 Donator Moderation Voter
5 years ago
Edited 5 years ago

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?

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 years ago

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
0
Thank you for the help. KDarren12 705 — 5y
Ad

Answer this question