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
6 years ago
Edited 6 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.

1local targets = {workspace.Part, workspace.OtherPart}
2 
3for i,target in pairs(targets) do
4target:Destroy()
5end

Any help?

1 answer

Log in to vote
2
Answered by 6 years ago
Edited 6 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:

1pcall(function()
2    local targets = {workspace.Part,workspace.OtherPart}
3    for i = 1,#targets do
4        targets[i]:Destroy()
5    end
6end)

You can also use if statements to create a more conservative approach that does not require using the pcall function:

1local targets = {workspace:FindFirstChild('Part'),workspace:FindFirstChild('OtherPart')}
2for i = 1,#targets do
3    if targets[i] then targets[i]:Destroy() end
4end
0
Thank you for the help. KDarren12 705 — 6y
Ad

Answer this question