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

Why does this error on me? [pcall]

Asked by 9 years ago

I was looking through the function dump page, and saw pcall. When I tried testing it as so, I get 'Baseplate' is not a valid member of Workspace

Don't think I'm misspelling anything wrong. When I put in BasePlate, it prints yes

I'm trying to test the condition with an object that doesn't exist

oExists = function(thing)
local success,msg = pcall(function() return thing ~= nil end)
if success then
    return true
end
return false
end
print(oExists(workspace["Baseplate"]) and "yes" or "no")
0
pcall is almost never the answer. In particular, just reading this code, the function `pcall` is given can't ever error. BlueTaslem 18071 — 9y

1 answer

Log in to vote
2
Answered by 9 years ago

The problem is this part:

workspace["Baseplate"]

If there is no object named "Baseplate" in Workspace, that statement will error, as you are attempting to reference a nil value outside of the protected call. To make this function work as you would like it to, you could do something like this:


local oExists = function(directory, thing) local success = pcall(function() return not not directory[thing] end) return success end print(oExists(workspace, "Baseplate") and "yes" or "no")

But honestly, you could just use directory:FindFirstChild(string object_name), which is much easier.

Ad

Answer this question