Yesterday, I came across a video that really got to me. In the video, a guy admitted he didn’t know what xpcall is.
Explanation of xpcall()
Let me break it down for you – the key thing to know is that xpcall() is faster than the standard pcall() and doesn’t yield. Additionally, you can customize the error detector.
Comparison with ypcall()
I’ve noticed some folks asking about ypcall, but it essentially does the same thing as pcall(), so it’s not much help. (It even marks ypcall with crossed text).
If this info was useful to you, please give this post a thumbs up!
Thanks for going out of your way to create explanations for the different types of protected calls.
However, I have a bit of feedback. This tutorial lacks a few things.
It would be more useful if you included code examples of when normal pcall would be used instead of xpcall and and when xpcall would be used instead of pcall.
Addtionally, it’s not very detailed. The explanation of xpcall in the Creator Documentation is more detailed and gives us more information on how it works.
There’s also this tutorial which gives a detailed explanation on how each type of pcall works, which I would refer to more than this one.
There is no reason anyone should be using ypcall for 2 reasons:
It’s deprecated
At one point in time, pcall didn’t yield. Now it does though, which effectively made ypcall useless.
In short, examples and more detailed explanations on how how xpcall works and why we would use xpcall over pcall would be great
And pcall with if-statements will be faster than xpcall:
Code
local start = os.clock()
for _ = 0, 1e4 do
xpcall(function()
local res = math.random(0, 1)
if res == 1 then
error(res)
end
end, function(res)
math.random()
end)
end
local finish = os.clock()
local result1 = finish - start
print("xpcall:", result1)
local start = os.clock()
for _ = 0, 1e4 do
local s, m = pcall(function()
local res = math.random(0, 1)
if res == 1 then
error(res)
end
end)
if not s then
math.random()
end
end
local finish = os.clock()
local result2 = finish - start
print("pcall:", result2)
print("diff:", result1 - result2)